如何选择与SQL中不同行相同的列数据

时间:2014-05-29 11:59:26

标签: sql

使用SQL Select Query和以下结构表

Id  Name  Subject

07  anu   Maths
07  anu   English
07  anu   Hindi

我希望结果为

Id Name Sub1    Sub2     Sub3
07 Anu  Maths   English  Hindi

1 个答案:

答案 0 :(得分:1)

试试这个会帮到你

SELECT Name,
      MAX(CASE WHEN Subject = 'Maths' THEN Subject ELSE NULL END) [subject1],
      MAX(CASE WHEN Subject = 'English' THEN Subject ELSE NULL END) [subject2],
      MAX(CASE WHEN Subject = 'Hindi' THEN Subject ELSE NULL END) [subject3]
FROM Subject
GROUP BY Name