假设我在MSSQL表中有这些数据
type status a open b open a closed a closed a closed b open c closed
我可以运行此查询来获取这样的表
select type,count(*) from table where status = 'open'
a 1 b 2
然后我可以再做一次查询
select type,count(*) from table where status = 'closed'
a 2 c 1
如何编写一个向我显示此类表格的查询
type open closed a 1 2 b 2 0 c 0 1
答案 0 :(得分:3)
这将产生您想要的结果
select type,
SUM(case when status = 'open' then 1 else 0 end) as [Open],
SUM(case when status = 'closed' then 1 else 0 end) as [Closed]
from table
group by type
答案 1 :(得分:0)
您可以使用PIVOT,查看BOL或搜索任何SQL网站以获取一些使用示例。
答案 2 :(得分:0)
在SQL 2005中创建了表,并使用pivot命令确认了以下工作:
select *
from (select type, status from table) test
pivot ( count(status) for status in ([Open], [Closed] )) pivottable