2

在 SQL Server 2008 中,我有一个查询。当我select在我的表上使用查询时Student,我得到一个这样的结果集:

Total   Subject            Class
20       Chemistry          Standard -12
30        Physics           Standard -12
94        Biology           Standard -12
0         Maths             Standard -12

5       Chemistry           Standard -11
45       Physics            Standard -11
50       Biology            Standard -11
45        Maths             Standard -11

但现在我的要求是我需要以不同的方式格式化它——像这样:

                   Chemistry Biology Physics Maths
Standard - 12     20       94      30      0
Standard - 11      5       50      45      45
4

2 回答 2

3

询问:

SQLFIDDLE示例

SELECT *
FROM (SELECT Class,
      Subject,
      Total 
      FROM Student ) s
pivot ( SUM(Total)
        FOR [Subject] IN ([Chemistry], [Physics], [Biology], [Maths])
       ) piv

结果:

|        CLASS | CHEMISTRY | PHYSICS | BIOLOGY | MATHS |
--------------------------------------------------------
| Standard -11 |         5 |      45 |      50 |    45 |
| Standard -12 |        20 |      30 |      94 |     0 |
于 2013-06-28T09:15:12.607 回答
1

我相信你对班级和科目组合有独特的行。

在这种情况下,您可以使用以下查询 -

select class,
       max(case
             when subject = 'Chemistry' then
              total
             else
              0
           end) as Chemistry,
       max(case
             when subject = 'Biology' then
              total
             else
              0
           end) as Biology,
       max(case
             when subject = 'Physics' then
              total
             else
              0
           end) as Physics,
       max(case
             when subject = 'Maths' then
              total
             else
              0
           end) as Maths
  from your_table_name
 group by class
于 2013-06-28T08:39:43.787 回答