将 table 列转为行

Turn the table columns as rows

我有具有以下结构的 table。我需要将列转为行

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

有 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

您可以将 table 与日期列表交叉连接,然后使用 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

试试这个:使用 unpivot

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'));

输出: