如何根据列值在单个列中显示表的多个列?

时间:2016-11-06 21:10:18

标签: sql sql-server

我有一张这样的表:

main table 现在我想编写一个可以显示以下数据的查询:

desire result

我该怎么做?请有人帮帮我吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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