左边连接一个表自己将行收集到列中

时间:2015-04-01 19:58:18

标签: mysql sql left-join

我正在尝试编写一个视图,将表格的数据从垂直“旋转”到水平:

Uid    Name    Key     Value
 1      User1   data1   resultX
 2      User1   data2   resultY
 3      User1   data3   resultZ
 4      User2   data1   resultX
 5      User2   data3   resultZ

结果数据集应如下所示:

Name     Val1       Val2       Val3
 User1    resultX    resultY    resultZ
 User2    resultX    NULL       resultZ

棘手的是我还想显示空值字段。 我可以或多或少地实现这一点的唯一方法是使用这样的子选择 (或多或少意味着:这仅适用于密钥= data1存在的数据集):

SELECT 
    t1.name
    , t1.value AS val1
    , t2.value AS val2 
    , t3.value AS val3 
FROM (
    SELECT
        name
        , value
    FROM
        tableA
    WHERE
        key = 'data1'
) t1
LEFT JOIN (
    SELECT
        name
        , value
    FROM
        tableA
    WHERE
        key = 'data2'
) t2
    ON t1.name= t2.name
LEFT JOIN (
    SELECT
        name
        , value
    FROM
        tableA
    WHERE
        key = 'data3'
) t3
    ON t1.name= t3.name
;

有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

如果您的案例中有data1,data2 and data3等已知项目,则可以使用以下技巧

select 
name,
max(case when `key` = 'data1' then value end) as val1,
max(case when `key` = 'data2' then value end) as val2,
max(case when `key` = 'data3' then value end) as val3  
from tableA group by name ;