数据透视表的核心就是按照行、列同时分组,然后对同时满足行、列条件的值进行某种聚合运算。
在sql中实现pivot功能是用group by+case when组合语句。
before:
after:
实现的语句是:
select
order_num,
sum(case when order_item=1 then quantity end) as one,
sum(case when order_item=2 then quantity end) as two,
sum(case when order_item=3 then quantity end) as three,
sum(case when order_item=4 then quantity end) as four
from
orderitems
group by order_num;
order_num作为行分组使用group by,item使用case when语句做列分组,对quantity进行求和。
从结果倒推,使用sql语句实现数据透视表功能。