代码之家  ›  专栏  ›  技术社区  ›  sri

在impala中将列转换为行

  •  0
  • sri  · 技术社区  · 8 年前

    我有以下三张桌子

    tab_2016
    +-----+------+---------+
    |  id | month| salary  |
    +-----+------+---------+
    | 002 |  aug |  500    |
    | 002 |  sep |  400    |
    +-----+------+---------+
    
    
    tab_2017    
    +-----+------+---------+
    |  id | month| salary  |
    +-----+------+---------+
    | 001 |  jan | 1000    |
    | 001 |  jul | 2000    |
    | 002 |  aug |  500    |
    | 002 |  sep |  400    |
    +-----+------+---------+
    
    tab_2018    
    +-----+------+---------+
    |  id | month| salary  |
    +-----+------+---------+
    | 001 |  feb | 500     |
    | 001 |  jul | 400     |
    | 002 |  aug | 300     |
    | 002 |  sep | 400     |
    +-----+------+---------+
    

    我正在努力获得id:001的年薪总额,如下所示。

        +-----+---------+---------+-----------+
        |  id | YR_2017 | YR_2018 |  YR_2016  | 
        +-----+---------+---------+-----------+
        | 001 |  3000   | 900     |    0      |
        +-----+---------+---------+-----------+
    

    我尝试过使用case语句来跟踪查询,但没有得到理想的结果。我也尝试过使用联接,但当表的数量增加时,根据年份动态生成查询变得越来越困难。

        select id,
        case 
        when YR=2017
        then
        sal end as YR_2017,
        case 
        when YR=2018
        then
        sal end as YR_2018,
    case 
        when YR=2016
        then
        sal end as YR_2016
    
     from 
        (select id,sum(salary) as sal,"2017" as YR   from tab_2017 where id=001 group by id
        union all
        select id,sum(salary) as  sal,"2018" as YR from tab_2018 where id=001 group by id
         union all
    select id,sum(salary) as  sal,"2016" as YR from tab_2016 where id=001 group by id
    ) as a
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Kishore    8 年前
    select a.id, a.YR_2017, b.YR_2018, If(c.YR_2016 IS NULL,0,c.YR_2016 ) from (select id,sum(salary) as YR_2017   from tab_2017 where id=1 group by id) a
    JOIN (select id,sum(salary) as YR_2018 from tab_2018 where id=1 group by id) b
    on a.id=b.id
    LEFT JOIN (select id,sum(salary) as YR_2016 from tab_2016 where id=1 group by id) c
    on b.id=c.id;
    

    这是一个粗略的问题,我还没有测试过