多行合并为具有标题名称的单行



我的问题就像这个问题,但我正在从不同的表中获取数据:

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

我该怎么做?

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

试试这个:

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

演示

相关内容

  • 没有找到相关文章

最新更新