2016-11-06 127 views
1

我有這樣一個表:如何根據列值在單個列中顯示多個表的列?

main table 現在我想編寫一個查詢,可以顯示這些數據如下:

desire result

我怎樣才能做到這一點?有人可以幫我嗎?

+7

這是在表示層... SQL-服務器較好地解決了不允許與*列組*,其中有一些像一個結果a * meta-header * ...您不能一次又一次地使用同一個列名,(至少如果您想在任何嵌入式上下文中使用此結果集)。 – Shnugo

+3

**請!**:請勿插入圖片!如果有人想幫助你,你必須手動鍵入你的數據。請閱讀[如何創建一個MCVE](http://stackoverflow.com/help/mcve) – Shnugo

+0

@Shnugo謝謝你。如果你知道我的問題,請刪除標題並給我一個答案。我只想要數據,而不是標題 – Mohsen

回答

0
SELECT Grade AS ISG, 
      P1AR, P1SM1, P1SM2, 
      P2AR, P2SM1, P2SM2, 
      P3AR, P3SM1, P3SM2 
    FROM 
    (
      SELECT Grade, 
        col = 'P' + CAST(Process AS NVARCHAR) +col, 
        value 
      FROM yourTable 

      CROSS APPLY 
      (
       VALUES 
       ('AR', AR), 
       ('SM1', SM1), 
       ('SM2', SM2) 
      ) c(col, value) 
    ) d 
    PIVOT 
    (
      MAX(value) 
      FOR col IN (P1AR, P1SM1, P1SM2, 
         P2AR, P2SM1, P2SM2, 
         P3AR, P3SM1, P3SM2) 
    ) piv 
0

另一種方式來寫這個查詢:

SELECT 
a.Grade AS ISG, 
a.AR AS P1AR, 
a.SM1 AS P1SM1, 
a.SM2 AS P1SM2, 

b.AR AS P2AR, 
b.SM1 AS P2SM1, 
b.SM2 AS P2SM2, 

c.AR AS P3AR, 
c.SM1 AS P3SM1, 
c.SM2 AS P3SM2  
FROM yourTable a 
INNER JOIN yourTable b 
ON  a.Grade = b.Grade 
INNER JOIN yourTable c 
ON  a.Grade = c.Grade 

where a.Process = 1 and 
     b.Process = 2 and 
     c.Process = 3 
相關問題