带有标题名称的多行到单行

时间:2012-04-17 06:50:14

标签: sql sql-server database pivot pivot-without-aggregate

我的问题就像this question,但我从不同的表中获取数据:

Name   ID  Subject-name    obtained-marks
gumman  9   English              3
gumman  9   Islamic-Studies      4
gumman  9   Pak Studies          3 

我想要这样的输出:

ID   Name   English   Islamic-Studies   Pak-studies
9   gumman   3             4                3

我该怎么做?

2 个答案:

答案 0 :(得分:4)

select ID,
       Name,
       [English],
       [Islamic-Studies],
       [Pak Studies]
from YourTable 
pivot
  (
    min([obtained-marks]) for [Subject-name] in ([English],
                                                 [Islamic-Studies],
                                                 [Pak Studies])
  ) as P

答案 1 :(得分:2)

试试这个:

Select s.ID, s.Name, 
       MAX(case WHEN s.SubjectName = 'English'         THEN s.ObtainedMarks end) as 'English',
       MAX(case WHEN s.SubjectName = 'Islamic-Studies' THEN s.ObtainedMarks end) as 'Islamic-Studies',
       MAX(case WHEN s.SubjectName = 'Pak Studies'     THEN s.ObtainedMarks end) as 'Pak-studies'
From Students s
GROUP BY s.ID, s.Name

DEMO