sql将数据横向展示

时间:2025-03-06 07:44:04

IF(expr1,expr2,expr3);
当expr1为true时返回expr2,当expr2为false时返回expr3;
重点:group by+if语句+聚合函数(max、sum)组合使用
例如:表一为商品表 【product】

product_id product_name
1 旺仔小馒头
2 旺仔QQ糖

表二为商品明细表 【product_item】

product_item_id unit unit_type price product_id
1 0 10 1
2 1 100 1
3 0 8 2
4 1 160 2

查询每种商品不同规格的价格
select
p.product_name as ‘商品名称’,
max(if(i.unit_type=0,unit,‘’)) as ‘小包装单位’,
max(if(i.unit_type=1,unit,‘’)) as ‘大包装单位’,
max(if(i.unit_type=0,price,0)) as ‘小包装价格’,
max(if(i.unit_type=1,price,0)) as ‘大包装价格’
from product as p
left join product_item as i on p.product_id=i.product_id
group by p.product_id

查询结果:

商品名称 小包装单位 大包装单位 小包装价格 大包装价格
旺仔小馒头 10 100
旺仔QQ糖 8 160