Sql Server系列:聚合函式

libingql發表於2014-11-30

1 SUM

  SUM是一個求和函式,返回指定列值的總和。SUM 只能用於數字列。 其中忽略 Null 值。

  語法

SUM ( [ ALL | DISTINCT ] expression )
   OVER ( [ partition_by_clause ] order_by_clause )  

  示例

SELECT SUM([UnitsInStock]) FROM [dbo].[Product]
SELECT SUM(DISTINCT([UnitsInStock])) FROM [dbo].[Product]

  SUM可以與GROUP BY一起使用,計算每個分組的總和。

SELECT [CategoryID],SUM([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

2 AVG

  返回組中各值的平均值。 其中忽略 Null 值。

  語法

AVG ( [ ALL | DISTINCT ] expression )
   OVER ( [ partition_by_clause ] order_by_clause )  

  示例

SELECT AVG([UnitsInStock]) FROM [dbo].[Product]
SELECT [CategoryID],AVG([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

3 MAX

  返回表示式中的最大值。

  語法

MAX ( [ ALL | DISTINCT ] expression )
   OVER ( [ partition_by_clause ] order_by_clause )  

  示例

SELECT MAX([UnitsInStock]) FROM [dbo].[Product]
SELECT [CategoryID],MAX([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

4 MIN

  返回表示式中的最小值。

  語法

MIN ( [ ALL | DISTINCT ] expression )
   OVER ( [ partition_by_clause ] order_by_clause )  

  示例

SELECT MIN([UnitsInStock]) FROM [dbo].[Product]
SELECT [CategoryID],MIN([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

  在查詢語句中同時使用MIN、MAX函式

SELECT [CategoryID],MIN([UnitsInStock]), MAX([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

  where條件過濾

SELECT [CategoryID],MIN([UnitsInStock]), MAX([UnitsInStock])
FROM [dbo].[Product]
WHERE [CategoryID] IN (1, 2, 3)
GROUP BY [CategoryID]

5 COUNT

  返回組中的項數。 COUNT 與 COUNT_BIG 函式類似。 兩個函式唯一的差別是它們的返回值。 COUNT 始終返回 int 資料型別值。 COUNT_BIG 始終返回 bigint 資料型別值。

  語法

COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } ) 
    OVER ( [ partition_by_clause ] order_by_clause )

  示例

SELECT COUNT([UnitsInStock]) FROM [dbo].[Product]
SELECT [CategoryID],COUNT([UnitsInStock])
FROM [dbo].[Product]
GROUP BY [CategoryID]

  COUNT(*)函式用於計算查詢中返回的行數。

SELECT COUNT(*) FROM [dbo].[Product]

  COUNT函式的其他計算形式,如COUNT(1)、COUNT([PrimaryKey])、COUNT([ColumnName]),COUNT()函式會忽略NULL的記錄,在使用COUNT([ColumnName])計算行數時,欄位ColumnName值為NULL的記錄不會計算。

SELECT COUNT([ProductName]) FROM [dbo].[Product]

  等價於:

SELECT COUNT([ProductName]) FROM [dbo].[Product]
WHERE [ProductName] IS NOT NULL

  在COUNT()方法中使用DISTINCT

SELECT COUNT(DISTINCT [CategoryID]) FROM [dbo].[Product]

6 HAVING

  HAVING子句僅用於帶有GROUP BY子句的查詢語句中,WHERE子句用於每一行(在變成一個組的某一部分之前),而HAVING子句用於分組的聚合值。

SELECT [CategoryID], COUNT(*) AS Products
FROM [dbo].[Product]
GROUP BY [CategoryID]
SELECT [CategoryID], COUNT(*) AS Products
FROM [dbo].[Product]
WHERE [Quantity] >= 10
GROUP BY [CategoryID]
SELECT [CategoryID], COUNT(*) AS Products
FROM [dbo].[Product]
WHERE [Quantity] >= 10
GROUP BY [CategoryID]
HAVING COUNT(*) > 1

相關文章