使用Unpivot转换SQL表

时间:2015-06-17 20:40:16

标签: sql database unpivot union-all

如果我有一个具有以下结构的表

ID NAME A1 A2 A3 B1 B2 B3

X ---- Y ------ 0 --- 1 --- 2 --- 3 --- 4 --- 5(破折号只是为了在标题下推送值)

如何将其转换为以下内容:

ID NAME LETTER 1 2 3

X ----ý---------- ------甲0-1-2

X ---ý------------乙----- 3-4-5

2 个答案:

答案 0 :(得分:0)

SELECT id, name, 'A' letter, a1 1, a2 2, a3 3 from example_table
UNION
SELECT id, name, 'B' letter, b1 1, b2 2, b3 3 from example_table

我不确定1,2,3是否可以作为列名;这可能与RDBMS有关。

答案 1 :(得分:0)

虽然我不认为这是一个可行的答案,但它可能会给你一些思考,因为它会在sql server中产生最终结果。

SELECT 
    upvt.id
    , upvt.name
    , left(label,1) AS letter
    , CASE
        WHEN left(label,1) = 'A' THEN MIN(value)
        WHEN left(label,1) = 'B' THEN MAX(value)
        END AS [1]
    , CASE
        WHEN left(label,1) = 'A' THEN MIN(value1)
        WHEN left(label,1) = 'B' THEN MAX(value1)
        END AS [2]
    , CASE
        WHEN left(label,1) = 'A' THEN MIN(value2)
        WHEN left(label,1) = 'B' THEN MAX(value2)
        END AS [3]
FROM example_table
UNPIVOT (
    value
    FOR label IN (a1,b1)
    ) upvt
INNER JOIN (
            SELECT 
                id
                , name
                , left(label1,1) AS letter
                , value1
            FROM example_table
            UNPIVOT (
                value1
                FOR label1 IN (a2,b2)
                ) upvt1 ) as b
    ON upvt.id = b.id
    AND upvt.name = b.name
INNER JOIN (
            SELECT 
                id
                , name
                , left(label2,1) AS letter
                , value2
            FROM example_table
            UNPIVOT (
                value2
                FOR label2 IN (a3,b3)
                ) upvt2 ) c
    ON upvt.id = c.id
    AND upvt.name = c.name
group by upvt.id, upvt.name, upvt.label

不完全是我所说的"生产就绪"。