我有一个分类表,如下所示,
我希望根据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
但是我不能进入价值观的专栏。
`
答案 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