为此恳求标题道歉!
我有以下需要转动的查询:
select name, flag,count(*) as [thecount]
from vwPopulationInformation
group by name, flag
它返回的样本是:
name flag thecount
Clea 1 309
Clea 0 2
DMS 1 18
DMS NULL 34
EMid 1 392
EMid NULL 436
EMid 0 45
EMidN 0 1
EMidN 1 167
EMidN NULL 31
...基本上我需要让我的支点回归
name yes no ? Total
Clea 309 0 0 309
DMS 18 0 34 52
EMid 392 45 436 873
EMidN 167 1 31 199
其中flag字段有点需要转换为:1 ='yes',0 ='no',NULL ='?'
我看过数据透视表示例,但无法理解它。有人可以帮忙吗?
答案 0 :(得分:2)
你没有指定你正在使用的数据库但是因为你提到了PIVOT,我假设是SQL Server。你可以使用:
select name,
coalesce(yes, 0) yes,
coalesce(no, 0) no,
coalesce([?], 0) [?],
coalesce(yes, 0) + coalesce(no, 0) + coalesce([?], 0) as Total
from
(
select name,
case
when flag = 1 then 'yes'
when flag = 0 then 'no'
when flag is null then '?' end flag,
thecount
from vwPopulationInformation
) src
pivot
(
sum(thecount)
for flag in (yes, no, [?])
) piv;