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

解答

sql 复制代码
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;
相关推荐
一位代码2 分钟前
mysql | 常见日期函数使用及格式转换方法
数据库·mysql
SelectDB13 分钟前
Apache Doris 4.0.2 版本正式发布
数据库·人工智能
杰克尼38 分钟前
mysql_day01
数据库·mysql
ccino .1 小时前
sql注入中过滤分隔符的测试方法
数据库·sql
Evan芙2 小时前
nginx核心配置总结,并实现nginx多虚拟主机
运维·数据库·nginx
Hello.Reader2 小时前
Flink SQL CREATE 语句从建表到 CTAS/RTAS,一次讲清
sql·flink·linq
amao99882 小时前
数据库--dataset design
数据库
山沐与山3 小时前
【数据库】PostgreSQL架构与索引深度剖析
数据库·postgresql·架构
不穿格子的程序员4 小时前
Redis篇6——Redis深度剖析:从单机到集群,Redis高可用进化史
数据库·redis·集群·主从·高可用·哨兵