面试题:oracle数据库行转列的问题

今天我一个学弟问了一个面试题:

有表A,结构如下:
A: p_ID p_Num s_id
1 10 01
1 12 02
2 8 01
3 11 01
3 8 03
其中: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代替。

答案是

select p_id,
sum(case when s_id = "1" then p_num else 0 end) s1_id,
sum(case when s_id = "2" then p_num else 0 end) s2_id,
sum(case when s_id = "3" then p_num else 0 end) s3_id
from A group by p_id

这其实是一个oracle的行转列的题目,以前做过,刚才问到我的时候,突然没反应过来,现在做个随笔,以便自己记住。

扫描二维码关注公众号,回复: 1158995 查看本文章

行转列  用sum函数   格式是sum(case when 条件 then 统计的列 else ... end ) 转完之后的列名

猜你喜欢

转载自www.cnblogs.com/zhyStudy/p/9112021.html