将表格列转为行

时间:2019-01-26 12:55:07

标签: sql oracle oracle11g unpivot

我的桌子结构如下。我需要将列变成行

ID  NAME      2011   2012
1   macbook   2      241
2   macbook   77     214
3   macbook   0      400
4   iphone    442    555

with tbl as (
 select  1 as id, 'macbook' as name, 2 as "2011", 241 as "2012" from dual union
 select  2 as id, 'macbook' as name, 77 as "2011", 214 as "2012" from dual union
 select  3 as id, 'macbook' as name, 0 as "2011", 400 as "2012" from dual union
 select  4 as id, 'iphone' as name, 442 as "2011", 555 as "2012" from dual
)
select * from tbl

我使用Oracle数据库,我试图通过使用unpivot函数解决问题,但是我对此进行了堆叠

我希望得到这样的结果

ID  NAME    DATE    SALES
1   macbook 2011    2
1   macbook 2012    241
2   macbook 2011    77
2   macbook 2012    214
3   macbook 2011    0
3   macbook 2012    400
4   iphone  2011    442
4   iphone  2012    555

3 个答案:

答案 0 :(得分:0)

有2个子查询,每个子查询分别获得每年的结果,然后是UNION:

select * from (
    select t.id, t.name, '2011' as "date", t."2011" as sales from tbl t  
    union all
    select t.id, t.name, '2012' as "date", t."2012" as sales from tbl t
) t
order by t.id, t.name, t."date"

请参见demo

答案 1 :(得分:0)

您可以将表与日期列表进行交叉联接,然后使用DECODE在每一行中提取相关的年销售额。

SELECT 
    t.id,
    t.name.
    t.dt "date",
    DECODE(t.dt, 2011, t."2011", 2012, t."2012", 0) sales
FROM mytable t
CROSS JOIN (
    SELECT 2011 dt FROM DUAL
    UNION SELECT 2012 FROM DUAL
) d
ORDER BY 1,2

答案 2 :(得分:0)

尝试一下:使用不可旋转

with tbl as (
 select  1 as id, 'macbook' as name, 2 as "2011", 241 as "2012" from dual union
 select  2 as id, 'macbook' as name, 77 as "2011", 214 as "2012" from dual union
 select  3 as id, 'macbook' as name, 0 as "2011", 400 as "2012" from dual union
 select  4 as id, 'iphone' as name, 442 as "2011", 555 as "2012" from dual
)
select * from tbl
UNPIVOT (SALES FOR "DATE" IN ("2011" AS '2011', "2012" AS '2012'));

输出:

enter image description here