MySQL行成列

时间:2015-07-07 08:44:52

标签: mysql dynamic pivot

对于我的一个项目,我面临一个独特的问题

当前表格输出:

CaseKey CustomField Fruits  Electronics Sports

1       10320       Apples  null        null
1       10864       null    Laptops     null
1       10471       null    null        cricket
2       10320       Oranges null        null
2       10864       null    TV          null
2       10471       null    null        baseball

我想要的表结构是按CaseKey分组

CaseKey Fruits  Electronics Sports
1       Apples  Laptops     Cricket
2       Oranges TV          BaseBall

当前查询:

select j.pkey as CaseKey,cfv.customfield,
(CASE   
            WHEN cfv.customfield=10320
            THEN cfv.customvalue
        END)   Fruits,
        (CASE
            WHEN cfv.customfield=10864
            THEN cfv.customvalue
        END) AS Electronics,
        (
        CASE
            WHEN cfv.customfield=10310
            THEN cfv.customvalue
        END)Sports,


from 

basetable j

left join  customfieldvalue cfv on j.id=cfv.issue


       and cfv.customfield in (10320,10864,10471)

-- group by j.id

表结构:basetable

ID     CaseKey
 4000  1
 4001  2

customfieldvalue

ID ISSUE CUSTOMFIELD CUSTOMVALUE

1  4000  10320       Apples
2  4000  10864       Laptops
3  4000  10471       Cricket
4  4001  10320       Oranges
5  4001  10864       TV
6  4001  10471       BaseBall

您能告诉我如何实现这一结果吗?我想在Tableau中将此查询作为CustomSQL运行,因此我不确定高级SQL(如动态SQL,存储过程)是否可以在那里工作。寻找可以实现这一结果的传统SQL。

2 个答案:

答案 0 :(得分:1)

你可以尝试这个查询:(它对我有用,不能把小提琴做错..)

    SELECT CaseKey, CustomField, 
     IF(  `Fruits` IS NOT NULL ,  `Fruits` ,  (IF (`Electronics` IS NOT NULL,`Electronics`,`Sports` )) ) AS T
    FROM TableName

答案 1 :(得分:1)

您可以使用子查询,如下所示:

select
    CaseKey,
    (select customvalue from customfieldvalue where issue = b.id and customfield = 10320) as Fruits,
    (select customvalue from customfieldvalue where issue = b.id and customfield = 10864) as Electronics,
    (select customvalue from customfieldvalue where issue = b.id and customfield = 10471) as Sports
from
    basetable as b

哪个输出您想要的格式:

+---------+---------+-------------+----------+
| CaseKey | Fruits  | Electronics | Sports   |
+---------+---------+-------------+----------+
|       1 | Apples  | Laptops     | Cricket  |
|       2 | Oranges | TV          | Baseball |
+---------+---------+-------------+----------+

同样以Fiddle风格提供。