力扣SQL刷题12

题目1:
写出 SQL 语句,查找既是低脂又是可回收的产品编号,无需考虑排序。
在这里插入图片描述
在这里插入图片描述
代码实现:

select product_id  
from Products 
where low_fats = 'Y' and recyclable ='Y';

题目2:
写出一个 SQL 查询语句,查找每种产品在各个商店中的价格。
在这里插入图片描述
在这里插入图片描述
解题思路:这是一个将行转列的问题,使用group by分组计算,取每一组中对应情况的通过case when + 聚合函数(min,max,sum,avg)的结合,
求出相同产品在不同商店中的price
case when的使用方法如下:

CASE input_expression
WHEN when_expression THEN
result_expression [...n ] [
ELSE
else_result_expression
END

代码实现:

SELECT 
    product_id, 
    MIN(CASE store WHEN 'store1' THEN price ELSE null END) AS store1, 
    MIN(CASE store WHEN 'store2' THEN price ELSE null END) AS store2, 
    MIN(CASE store WHEN 'store3' THEN price ELSE null END) AS store3
FROM products
GROUP BY product_id

猜你喜欢

转载自blog.csdn.net/Txixi/article/details/115715907