SQL Pivot表列到行

时间:2015-10-07 19:10:52

标签: mysql sql pivot unpivot

我试图转换此表:

Date     |Col1    |Col2 |Col3|Col4|Col5|Col6|Col7|Col8

2/15/2015|Product1|MTD  |1   |2   |3   |4   |5   |6

2/15/2015|Product1|QTD  |11  |22  |33  |44  |55  |66

2/15/2015|Product1|YTD  |111 |222 |333 |444 |555 |666 

到此:

Date     |Col1    |Type|MTD|QTD|YTD

2/15/2015|Product1|Col3|1  |11 |111

2/15/2015|Product1|Col4|2  |22 |222

2/15/2015|Product1|Col5|3  |33 |333

2/15/2015|Product1|Col6|4  |44 |444

2/15/2015|Product1|Col7|5  |55 |555

2/15/2015|Product1|Col8|6  |66 |666

使用sql查询。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

可以与很多工会合作。

select MTD.date,MTD.col1,MTD.type,MTD.val as MTD,QTD.val as QTD,YTD.val as YTD 
from(
    select 'col3' type,date,col1,col3 as val from yourtable where col2 = 'MTD'
    union all
    select 'col4' type,date,col1,col4 from yourtable where col2 = 'MTD'
    union all
    select 'col5' type,date,col1,col5 from yourtable where col2 = 'MTD'
    union all
    select 'col6' type,date,col1,col6 from yourtable where col2 = 'MTD'
    union all
    select 'col7' type,date,col1,col7 from yourtable where col2 = 'MTD'
    union all
    select 'col8' type,date,col1,col8 from yourtable where col2 = 'MTD'
) MTD inner join (
    select 'col3' type,date,col1,col3 as val from yourtable where col2 = 'QTD'
    union all
    select 'col4' type,date,col1,col4 from yourtable where col2 = 'QTD'
    union all
    select 'col5' type,date,col1,col5 from yourtable where col2 = 'QTD'
    union all
    select 'col6' type,date,col1,col6 from yourtable where col2 = 'QTD'
    union all
    select 'col7' type,date,col1,col7 from yourtable where col2 = 'QTD'
    union all
    select 'col8' type,date,col1,col8 from yourtable where col2 = 'QTD'
) QTD on MTD.date = QTD.date and MTD.col1 = QTD.col1 and MTD.type = QTD.type
inner join (
    select 'col3' type,date,col1,col3 as val from yourtable where col2 = 'YTD'
    union all
    select 'col4' type,date,col1,col4 from yourtable where col2 = 'YTD'
    union all
    select 'col5' type,date,col1,col5 from yourtable where col2 = 'YTD'
    union all
    select 'col6' type,date,col1,col6 from yourtable where col2 = 'YTD'
    union all
    select 'col7' type,date,col1,col7 from yourtable where col2 = 'YTD'
    union all
    select 'col8' type,date,col1,col8 from yourtable where col2 = 'YTD'
) YTD on MTD.date = YTD.date and MTD.col1 = YTD.col1 and MTD.type = YTD.type