计算每个组返回的记录数

时间:2013-06-04 17:01:08

标签: sql-server aggregate-functions

我有一般的查询,例如:

SELECT col1, col2, col3, col4
FROM Table1 AS t1
GROUP BY col1, col2, col3, col4

它将返回类似于:

的表格
col1   col2   col3   col4    
data1  data2  data3  data4
data1  data2  data3  data5
data10 data11 data12 data13
data10 data11 data12 data14
data10 data11 data12 data15

我需要获取col1的计数才能显示data1两次返回,data10返回三次。该表应如下所示:

col1   col2   col3   col4   Count  
data1  data2  data3  data4  2
data1  data2  data3  data5  2
data10 data11 data12 data13 3
data10 data11 data12 data14 3
data10 data11 data12 data15 3

我在select语句中尝试了count(*),但这不起作用。

1 个答案:

答案 0 :(得分:5)

您可以使用OVER子句(SQL Server 2008 +):

SELECT col1, col2, col3, col4, COUNT(*) OVER(PARTITION BY col1) [Count]
FROM Table1 AS t1

结果是:

╔════════╦════════╦════════╦════════╦═══════╗
║  COL1  ║  COL2  ║  COL3  ║  COL4  ║ COUNT ║
╠════════╬════════╬════════╬════════╬═══════╣
║ data1  ║ data2  ║ data3  ║ data4  ║     2 ║
║ data1  ║ data2  ║ data3  ║ data5  ║     2 ║
║ data10 ║ data11 ║ data12 ║ data13 ║     3 ║
║ data10 ║ data11 ║ data12 ║ data14 ║     3 ║
║ data10 ║ data11 ║ data12 ║ data15 ║     3 ║
╚════════╩════════╩════════╩════════╩═══════╝

Here is a sqlfiddle及其演示。

<强>更新 如果您需要根据COUNT列进行过滤,则可以使用派生表或CTE:

派生表:

SELECT *
FROM (  SELECT col1, col2, col3, col4, COUNT(*) OVER(PARTITION BY col1) [Count]
        FROM Table1) A
WHERE [Count] > 2

CTE:

;WITH CTE AS
(
    SELECT col1, col2, col3, col4, COUNT(*) OVER(PARTITION BY col1) [Count]
    FROM Table1
)
SELECT *
FROM CTE 
WHERE [Count] > 2

结果:

╔════════╦════════╦════════╦════════╦═══════╗
║  COL1  ║  COL2  ║  COL3  ║  COL4  ║ COUNT ║
╠════════╬════════╬════════╬════════╬═══════╣
║ data10 ║ data11 ║ data12 ║ data13 ║     3 ║
║ data10 ║ data11 ║ data12 ║ data14 ║     3 ║
║ data10 ║ data11 ║ data12 ║ data15 ║     3 ║
╚════════╩════════╩════════╩════════╩═══════╝

sqlfiddle with this option