我希望制作一个select语句,选择一行中的所有不同项,并提供每个结果的总数
SELECT DISTINCT [Column 16] FROM [tab]
那就是我的TSQL走了多远
答案 0 :(得分:4)
您在寻找
吗?SELECT [Column 16], COUNT(*)
FROM [tab]
GROUP BY [Column 16]
--WITH ROLLUP (if you need to the total )
ORDER BY COUNT(*)
您可以将DESC
关键字附加到查询的末尾,例如ORDER BY COUNT(*) DESC
,如果您希望结果集按降序排序,或ASC
升序(默认为升序,你可以省略它。)
答案 1 :(得分:0)
当您GROUP BY
时,您会得到[第16栏]的明确列表。然后你可以使用它的聚合函数。
SELECT [Column 16], Sum ( [Column To Sum] ) Total_T1
FROM [tab]
Group By [Column 16]
如果您想按多列分组,它们应该出现在select和GROUP BY
中SELECT [Column 16], [Column 17], Sum ( [Column To Sum] ) Total_T1
FROM [tab]
Group By [Column 16], [Column 17]
您还可以指定多个聚合(这些聚合不会出现在group by
子句
SELECT [Column 16], [Column 17],
Sum ( [Column To Sum] ) Total_T1,
Count ( [Column To Sum] ) NumOf_T1,
Avg ( [Column To Sum] ) Avg_T1,
Min ( [Column To Sum] ) Min_T1,
Max ( [Column To Sum] ) Max_T1
FROM [tab]
Group By [Column 16], [Column 17]