我试图选择包含两列的结果集:
这句话(有点)说明了我试图做的事情:
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
答案 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 ;