在SQL Server列中计算相同的值

时间:2015-07-22 15:01:19

标签: sql sql-server sql-server-2008 count

我试图在列中计算相同的值,并希望它在那里返回一个计数。

| ITEM  | COUNT |
+-------+-------+
| GREEN |  1    |
| GREEN |  2    |
| GREEN |  3    |
| RED   |  1    |
| RED   |  2    |

我试过

ROW_NUMBER() OVER (ORDER BY ITEM) AS Row

但这只计算每一行1 - 1000

我将如何做到这一点?

3 个答案:

答案 0 :(得分:2)

尝试:

 ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY ITEM) AS Row

 ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY COUNT) AS Row

您可以像这样计算每个ITEM

COUNT(*) OVER (PARTITION BY ITEM) As CountByItem

答案 1 :(得分:1)

您需要在row_number函数中包含partition by子句。这使得row_number从每种新类型的项目重新开始。

ROW_NUMBER() OVER (PARTITION BY ITEM ORDER BY ITEM) AS Row

这会给你一个结果:

item    Row
GREEN   1
GREEN   2
GREEN   3
RED     1
RED     2

答案 2 :(得分:0)

此代码将计算表

中的相同值
SELECT item, COUNT(*)
FROM Table
Group by item