将某些行转换为sql / linq中的列

时间:2017-01-24 11:06:29

标签: c# sql linq

我有以下查询:

 SELECT 
     std. [Name]
     ,cl.Name as clsName
     ,stu.Name as student
     ,sub.Name as subject
     ,r.ObtainedMarks
  FROM [School.Model.SchoolContext].[dbo].[Standards] std
  join [School.Model.SchoolContext].[dbo].ClassSections cl on std.Id = cl.StandardId
  join [School.Model.SchoolContext].[dbo].Students stu on cl.id = stu.ClassSectionId
  join [School.Model.SchoolContext].[dbo].Subjects sub on std.id = sub.StandardId
  join [School.Model.SchoolContext].[dbo].Results  r on stu.Id = r.StudentId)

显示以下结果:

Table

我想为主题添加两列,例如英语和数学并删除列对象标记。获得的标记应显示在主题下。

请告诉我如何通过SQL查询或C#中的LINQ实现。

我在SQL中经历了Pivot查询,但我没有得到太多。

1 个答案:

答案 0 :(得分:1)

尝试这样,它可能不会工作,因为我没有测试它,但从这里继续,PIVOT是你想要的东西

  SELECT * FROM (
        SELECT 
            std. [Name]
            ,cl.Name as clsName
            ,stu.Name as student
            ,sub.Name as subject
            ,r.ObtainedMarks
        FROM [School.Model.SchoolContext].[dbo].[Standards] std
        join [School.Model.SchoolContext].[dbo].ClassSections cl on std.Id = cl.StandardId
        join [School.Model.SchoolContext].[dbo].Students stu on cl.id = stu.ClassSectionId
        join [School.Model.SchoolContext].[dbo].Subjects sub on std.id = sub.StandardId
        join [School.Model.SchoolContext].[dbo].Results  r on stu.Id = r.StudentId)
      ) SRC
    PIVOT
    (
        MAX(ObtainedMarks) FOR [Subject] IN ([English], [Maths])
    ) piv