0

この嘆願のタイトルについてお詫び申し上げます。

ピボットする必要がある次のクエリがあります。

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

ここで、フラグ フィールドはビットであり、次のように変換する必要があります: 1 = 'はい'、0 = 'いいえ'、および NULL = '?'

ピボット テーブルの例を見てきましたが、理解できません。誰でも助けてもらえますか?

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 に答える