如何根据列的唯一值对列进行分组,并根据其值计入不同的列?

时间:2016-12-07 06:25:51

标签: sql sql-server

我有一个分类表,如下所示,

This is my table

我希望根据scStatus值检索以下结果,并按catID

检索其计数组
catID | 0 | 2 | 3
----- |---|---|---
 2    | 1 | 0 | 1
 3    | 1 | 1 | 0
 4    | 2 | 0 | 1
 5    | 0 | 1 | 0

我尝试了这个,select catID,count(scStatus) as [Count] from tableName group by catID,scStatus order by catID但是我不能进入价值观的专栏。

`

2 个答案:

答案 0 :(得分:2)

使用透视查询:

SELECT catID,
       SUM(CASE WHEN scStatus = 0 THEN 1 ELSE 0 END) AS [0],
       SUM(CASE WHEN scStatus = 2 THEN 1 ELSE 0 END) AS [2],
       SUM(CASE WHEN scStatus = 3 THEN 1 ELSE 0 END) AS [3]
FROM Category
GROUP BY catID

答案 1 :(得分:1)

pivot 运算符

select      *
from        (select catID,scStatusvalue from t) t
                pivot (count(scStatusvalue) for scStatusvalue in ([0],[2],[3])) t