[英]Need assistance understanding pivot table
Apologies for this pleading title! 对此求情标题表示歉意!
I have the following query which I need to pivot: 我有以下需要调查的查询:
select name, flag,count(*) as [thecount]
from vwPopulationInformation
group by name, flag
a sample of what it returns is: 它返回的样本是:
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
...and basically I need to get my pivot to return ......基本上我需要让我的支点回归
name yes no ? Total
Clea 309 0 0 309
DMS 18 0 34 52
EMid 392 45 436 873
EMidN 167 1 31 199
where the flag field is a bit and needs to be translated to: 1 = 'yes', 0 = 'no', and NULL = '?' 其中flag字段有点需要转换为:1 ='yes',0 ='no',NULL ='?'
I've looked at pivot table examples but can't get my head around it. 我看过数据透视表的例子,但无法理解它。 Can anyone help please? 有人可以帮忙吗?
You did not specify what database you are using but since you mentioned PIVOT, I am assuming SQL Server. 你没有指定你正在使用的数据库但是因为你提到了PIVOT,我假设是SQL Server。 You could use: 你可以使用:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.