选择列中每个不同值的计数

时间:2014-08-05 11:32:31

标签: sql tsql

我试图选择包含两列的结果集:

  • 列的DISTINCT值。
  • 该值在表格列中显示的次数。

这句话(有点)说明了我试图做的事情:

SELECT DISTINCT ID AS X,
(SELECT COUNT(*) FROM #t WHERE ID = X)
FROM #t
ORDER BY X;

所需的结果集如下所示:

| ID   | COUNT
|------|------
| 0    | 12
| 1    | 16
| 2    | 4

3 个答案:

答案 0 :(得分:2)

SELECT   ID AS X,
         COUNT(*) AS "COUNT"
FROM     #t
GROUP BY ID
ORDER BY X

答案 1 :(得分:0)

这只是使用GROUP BY

的简单聚合
SELECT ID, COUNT(*)
FROM #t
GROUP BY ID
ORDER BY ID;

答案 2 :(得分:0)

SELECT   ID AS X,
         COUNT(1) AS "COUNT"
FROM     #t
GROUP BY ID
ORDER BY ID

使用Group By

您的查询(相关子查询)也应该有效。根据GordonLinoff的说法,在查询中将ID替换为ID,它应该可以正常工作。

SELECT DISTINCT ID AS X,
(SELECT COUNT(*) FROM #t WHERE ID = X)
FROM #t
ORDER BY ID ;