2013-06-28 18 views
2

在SQL Server 2008中,我有一個查詢。當我使用select查詢我的Student表,我得到一個結果集是這樣的:如何在SQL Server中進行格式化

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 

回答

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 
+0

親愛的Pratik,我嘗試過上面的查詢,但它不適合我。實際上以上的結果,我得到了「類」應用分組後,總數是該特定類的行數。 –

+0

@priyapatel對不起,我沒有得到爲什麼這個查詢不適合你的情況? –

+0

我不知道,我想用「樞軸」來實現這一點。 –

3

查詢:

SQLFIDDLEExample

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 | 
+0

謝謝它也可以。 –