0

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 条汤姆的记录。如

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 小提琴演示:http ://sqlfiddle.com/#!3/49fd0/19

于 2013-11-09T06:13:32.780 回答