0

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 = '?'

I've looked at pivot table examples but can't get my head around it. Can anyone help please?

4

1 回答 1

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;

请参阅带有演示的 SQL Fiddle

于 2013-05-14T14:35:13.407 回答