sql - Need assistance understanding pivot table -
apologies pleading title!
i have following query need pivot:
select name, flag,count(*) [thecount] vwpopulationinformation group name, flag
a sample of 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 need pivot 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 flag field bit , needs translated to: 1 = 'yes', 0 = 'no', , null = '?'
i've looked @ pivot table examples can't head around it. can please?
you did not specify database using since mentioned pivot, assuming sql server. use:
select name, coalesce(yes, 0) yes, coalesce(no, 0) no, coalesce([?], 0) [?], coalesce(yes, 0) + coalesce(no, 0) + coalesce([?], 0) total ( select name, case when flag = 1 'yes' when flag = 0 'no' when flag null '?' end flag, thecount vwpopulationinformation ) src pivot ( sum(thecount) flag in (yes, no, [?]) ) piv;
see sql fiddle demo
Comments
Post a Comment