Sql Server系列:聚合函数

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
posted @ 2014-11-30 17:56  libingql  阅读(4420)  评论(0编辑  收藏  举报