SQL练习-行转列

SQL执行顺序

from --> join --> on --> where --> group by ---> select后面的普通字段,聚合函数count,sum ---> having ---> distinct ---> order by ---> limit

行转列

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

例1

yearmonthamount
199111.1
199121.2
199131.3
199141.4
199212.1
199222.2
199232.3
199242.4

查成这样一个效果

yearm1m2m3m4
19911.11.21.31.4
19922.12.22.32.4
# if(condition,true,false)
select year,
	   sum(if(month='1',amount,0)) as m1,
	   sum(if(month='1',amount,0)) as m2,
	   sum(if(month='1',amount,0)) as m3,
	   sum(if(month='1',amount,0)) as m4 
from table1 group by year

# case field when value then true else false end
select year,
	   sum(CASE month WHEN '1' THEN amount ELSE '0' END) as m1,
	   sum(CASE month WHEN '2' THEN amount ELSE '0' END) as m2,
	   sum(CASE month WHEN '3' THEN amount ELSE '0' END) as m3,
	   sum(CASE month WHEN '4' THEN amount ELSE '0' END) as m4 
from table1 group by year

例2

有表A,结构如下:
在这里插入图片描述
其中:p_ID为产品ID,p_Num为产品库存量,s_id为仓库ID。
请用SQL语句实现将上表中的数据合并,合并后的数据为:
p_ID s1_id s2_id s3_id
1	 10     12 		0
2 	 8  	0 		0
3 	 11 	0 		8

其中:s1_id为仓库1的库存量,s2_id为仓库2的库存量,s3_id为仓库3的库存量。
如果该产品在某仓库中无库存量,那么就是0代替。

# if(condition,true,false)
select pid,
       sum(if(sid=1,pnum,0)) as s1_num,
	   sum(if(sid=2,pnum,0)) as s2_num,
	   sum(if(sid=3,pnum,0)) as s3_num
from table2 group by pid

# case field when value then true else false end
select pid,
       sum(CASE sid WHEN 1 THEN pnum ELSE 0 END) as s1_num,
       sum(CASE sid WHEN 2 THEN pnum ELSE 0 END) as s2_num,
	   sum(CASE sid WHEN 3 THEN pnum ELSE 0 END) as s3_num
from table2 group by pid

例3

在这里插入图片描述
统计每日胜负结果
在这里插入图片描述

# if(condition,true,false)
select ddate,
       count(if(dresult='胜',1,null)) as '胜',
       count(if(dresult='负',1,null)) as '负'
from table3 group by ddate;

# case field when value then true else false end
select ddate,
       count(CASE dresult WHEN '胜' THEN 1 ELSE null END) as '胜',
       count(CASE dresult WHEN '负' THEN 1 ELSE null END) as '负'
from table3 group by ddate;

#注意:这里count里case-when的部分,不满足的情况else时不能简单的用0,需要是null,因为count(0)也会统计为一条记录。【使用sum的时候可以给0。】
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值