0

1つのフィールドの値に基づいてテーブルをより多くのフィールドに展開するSQL方法

たとえば、次のようなものがあります。

ID   Name Age  YearQuarter Points
1    Tom   13   20131      100
1    Tom   13   20132      99
3    May   13   20133       98

私は欲しい

ID   Name Age   Points20131  Points20132  Points20133
1    Tom   13   100           99           NA
3    May   13   NA            NA           98

私は何かを試してみました

SELECT ID, Name,Age, Points as 'Points20131', 'NA' as 'Points20132', 'NA' as 'Point20133'
FROM table where YearQuarter = 20131
UNION
SELECT ID, Name,Age, 'NA' as 'Points20131', Points  as 'Points20132', 'NA' as 'Point20133'
FROM table where YearQuarter = 20132
UNION
SELECT ID, Name,Age, 'NA' as 'Points20131',  'NA'  as 'Points20132', Points as 'Point20133'
FROM table where YearQuarter = 20133

しかし、これは 2 つの Tom のレコードを生成します。そのような

ID   Name Age   Points20131  Points20132  Points20133
1    Tom   13   100           NA           NA
2    Tom   13   NA            99           NA
3    May   13   NA            NA           98

これを修正する方法は?

ありがとう

4

1 に答える 1

0

CASE WHEN を試す

SELECT MIN(tt.ID) as ID, 
       tt.Name,
       tt.Age, 
       ISNULL(CAST(SUM(Points20131) as varchar(10)),'NA') as 'Points20131',
       ISNULL(CAST(SUM(Points20132) as varchar(10)),'NA') as 'Points20132',
       ISNULL(CAST(SUM(Points20133) as varchar(10)),'NA') as 'Points20133'
FROM
(
   SELECT ID, 
          Name,
          Age, 
          CASE WHEN YearQuarter = '20131' THEN Points ELSE NULL END as 'Points20131', 
          CASE WHEN YearQuarter = '20132' THEN Points ELSE NULL END as 'Points20132', 
          CASE WHEN YearQuarter = '20133' THEN Points ELSE NULL END as 'Points20133' 
   FROM Test
) tt
GROUP BY tt.NAME, tt.Age
ORDER BY MIN(tt.ID)

SQL Fiddle デモ: http://sqlfiddle.com/#!3/49fd0/19

于 2013-11-09T06:13:32.780 に答える