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;
相关推荐
geovindu3 小时前
sql:SQL Pagination and Limiting Results using PorstgreSQL 18.0
大数据·数据仓库·sql·postgresql·数据库开发·数据库架构·1024程序员节
不脱发的程序猿4 小时前
纳指ETF量化策略
数据库·人工智能·1024程序员节
程序员塔塔喵5 小时前
【MySQL篇|第一篇】索引失效的情况
数据库·mysql·索引失效
北京青蓝智慧马老师5 小时前
比外部黑客更难防的,是那个有权限的自己人(3 个脱敏复盘)
大数据·数据库·人工智能
笃行3506 小时前
拆一台数据集成产品:KFS 的骨架、肌肉和神经
数据库
4SAPI6 小时前
搭建 AI 数据分析工具大模型 API 选型指南
数据库·人工智能·架构·php·1024程序员节
码士集团小青8 小时前
面霸篇:高频 Java 基础问题(核心卷一)
linux·服务器·数据库·redis·缓存·1024程序员节
LMT流氓兔9 小时前
第五单元——第十二课:把脚本整理成项目
java·数据库·python·langchain·1024程序员节
cuijiecheng20189 小时前
WeFlow 无法使用怎么办?一次数据库组件到期问题的排查与修复
数据库·oracle
一条泥憨鱼9 小时前
【Redis | 黑马点评】附近商铺功能源码解读
数据库·redis·缓存