sql-行转列(转置)

- 行转列的常规做法是,group by+sum(if())【或count(if())】

例题
已知

year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4

查成这样一个结果

year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4

解答

use test_sql;
set hive.exec.mode.local.auto=true;
create table table2(year int,month int ,amount double) ;
insert overwrite table table2 values
           (1991,1,1.1),
           (1991,2,1.2),
           (1991,3,1.3),
           (1991,4,1.4),
           (1992,1,2.1),
           (1992,2,2.2),
           (1992,3,2.3),
           (1992,4,2.4);
select * from table2;


--行转列
--常规做法是,group by+sum(if())
--SQLserver中有pivot专门用来行转列
--原始写法
select 
	year
    ,sum(a) as m1
    ,sum(b) as m2
    ,sum(c) as m3
    ,sum(d) as m4
from(
	select 
		*
        ,if(month=1,amount,0) a
        ,if(month=2,amount,0) b
        ,if(month=3,amount,0) c
        ,if(month=4,amount,0) d
    from table2 ) t
group by t.year;
--简化写法
select 
	year,
	,sum(if(month=1,amount,0)) m1
	,sum(if(month=2,amount,0)) m2
    ,sum(if(month=3,amount,0)) m3
    ,sum(if(month=4,amount,0)) m4
from table2
group by year;

相关推荐

  1. sql-()

    2024-05-13 11:14:03       12 阅读
  2. sql-2()

    2024-05-13 11:14:03       14 阅读
  3. sql-3()

    2024-05-13 11:14:03       10 阅读
  4. oracle 转行

    2024-05-13 11:14:03       7 阅读
  5. Hive数据仓库

    2024-05-13 11:14:03       28 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-13 11:14:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-13 11:14:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-13 11:14:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-13 11:14:03       18 阅读

热门阅读

  1. 母亲节祝福html源码示例

    2024-05-13 11:14:03       10 阅读
  2. Es6 Generator 生成器函数

    2024-05-13 11:14:03       8 阅读
  3. vben框架是什么

    2024-05-13 11:14:03       12 阅读
  4. 新闻标题抓取

    2024-05-13 11:14:03       12 阅读
  5. 【学习笔记】C++每日一记

    2024-05-13 11:14:03       12 阅读
  6. Python小程序 - 文件处理1(使用AI工具)

    2024-05-13 11:14:03       11 阅读
  7. 规则引擎drools Part5

    2024-05-13 11:14:03       9 阅读
  8. 开发一款抓大鹅游戏

    2024-05-13 11:14:03       13 阅读
  9. Debug: Pytorch dataloaders OSError: Bad file descriptor

    2024-05-13 11:14:03       15 阅读