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;
相关推荐
m0_5613596710 小时前
超越Python:下一步该学什么编程语言?
jvm·数据库·python
mango_mangojuice10 小时前
Linux学习笔记 1.19
linux·服务器·数据库·笔记·学习
TGITCIC11 小时前
丢掉向量数据库!推理型 RAG 正在重新定义长文档问答的准确边界
数据库·ai大模型·推理·ai搜索·大模型ai·rag增强检索·ai检索
xfhuangfu11 小时前
Oracle AI db 26ai中借助dbca创建pdb的过程
数据库·oracle
heze0911 小时前
sqli-labs-Less-28a
数据库·mysql·网络安全
久违81611 小时前
SQL注入攻击核心技术深度总结
数据库·sql·oracle
2401_8914504612 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
helloworldandy12 小时前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
「光与松果」12 小时前
Oracle中v$session视图用法
数据库·oracle
木辰風12 小时前
PLSQL自定义自动替换(AutoReplace)
java·数据库·sql