连接多个查询导致分隔列

时间:2015-05-19 06:47:42

标签: sql-server

你好每个人我有3个查询,当我使用union时它给我3行我想将3行转换成列我怎么能这样做请帮助我

这是我的查询

( select count(*) As TotalCount from Detail_User 
where userkey = 172 ) 
--union
( select count(*) As ICount1 from Detail_User 
where Parent_Name = 'A' and userkey = 172 )
--union
( select count(*) As ICount2 from Detail_User 
where Parent_Name = 'B' and userkey = 172 )

它给我一些这样的东西

TotalCount
2
3
5

我想要这样的东西

TotalCount ICount1 ICount2
2          3       5        

1 个答案:

答案 0 :(得分:2)

不要做UNION,在CASE WHEN中使用SELECT

select
count(*) As TotalCount,
SUM(CASE WHEN Parent_Name = 'A' THEN 1 ELSE 0 END) as ICount1 ,
SUM(CASE WHEN Parent_Name = 'B' THEN 1 ELSE 0 END) as ICount2 
from Detail_User 
where userkey = 172