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;
相关推荐
CodexDave9 小时前
PostgreSQL 明明有索引却选了 Nested Loop:从行数误判修正执行计划
数据库·postgresql·执行计划·扩展统计·nestedloop
czhaii10 小时前
STC ai助手单片机工程项目创建实例
数据库·mongodb
山峰哥11 小时前
数据库性能救星:Explain执行计划深度拆解
服务器·开发语言·数据库·sql·启发式算法
oradh11 小时前
Oracle 11g rac IP地址修改(public ip、vip、scan ip、priviate ip)
数据库·tcp/ip·oracle·rac ip地址修改
YOU OU12 小时前
Redis哨兵 & 集群
数据库·redis·sentinel
小罗水12 小时前
第8章 文档解析与文本切片
数据库·spring·spring cloud·微服务
瞬间&永恒~12 小时前
【MySQL】 主从复制多拓扑搭建实验
运维·数据库·mysql·云原生
han_hanker12 小时前
sql语法 DECODE, CASE ... WHEN
数据库·sql·oracle
井川廊咏13 小时前
vi 删除指定范围的行,不用再反复按 dd
数据库·mysql
z落落13 小时前
StudentInfo表 分页、增删改 存储过程+C# WinForm 存储过程实现分页和增删改查
数据库·sql·mysql