您可以使用该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 ║
╚════════╩════════╩════════╩════════╩═══════╝
这是一个带有演示的sqlfiddle 。
UPDATE
如果需要基于COUNT
列进行过滤,可以使用派生表或 CTE:
派生表:
SELECT *
FROM ( SELECT col1, col2, col3, col4, COUNT(*) OVER(PARTITION BY col1) [Count]
FROM Table1) A
WHERE [Count] > 2
热电偶:
;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。