[leetcode数据库03] 1777. 每家商店的产品价格

leetcode数据库题目,简单题,面试中出现频率约为40%

题目描述:

表:Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store       | enum    |
| price       | int     |
+-------------+---------+
(product_id,store) 是这个表的主键。
store 字段是枚举类型,它的取值为以下三种 ('store1', 'store2', 'store3') 。
price 是该商品在这家商店中的价格。
 

写出一个 SQL 查询语句,查找每种产品在各个商店中的价格。

可以以 任何顺序 输出结果。

查询结果格式如下例所示:

Products 表:
+-------------+--------+-------+
| product_id  | store  | price |
+-------------+--------+-------+
| 0           | store1 | 95    |
| 0           | store3 | 105   |
| 0           | store2 | 100   |
| 1           | store1 | 70    |
| 1           | store3 | 80    |
+-------------+--------+-------+
Result 表:
+-------------+--------+--------+--------+
| product_id  | store1 | store2 | store3 |
+-------------+--------+--------+--------+
| 0           | 95     | 100    | 105    |
| 1           | 70     | null   | 80     |
+-------------+--------+--------+--------+
产品 0 的价格在商店 1 为 95 ,商店 2 为 100 ,商店 3 为 105 。
产品 1 的价格在商店 1 为 70 ,商店 3 的产品 1 价格为 80 ,但在商店 2 中没有销售。

题目答案:

-- 解法1:
select product_id,
sum(if(store='store1',price,null)) store1,
sum(if(store='store2',price,null)) store2,
sum(if(store='store3',price,null)) store3
from Products
group by product_id

-- 解法2
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

-- 解法3
select p1.product_id,
(select price from Products where product_id = p1.product_id and store = 'store1') as store1,
(select price from Products where product_id = p1.product_id and store = 'store2') as store2,
(select price from Products where product_id = p1.product_id and store = 'store3') as store3
from Products p1 
group by p1.product_id

先执行group by分组,

题目根据商品id将数据分为2组,0组有2条数据,1组有3条数据,那么怎么组合出来我想要的数据结果呢?

在select里面使用case...when,

如果符合store1的条件,那么就展示store1的那条数据,分组中同行以及同列其他为null,

如果符合store2的条件,那么就展示store2的数据,分组中同行以及同列其他为null。

如果符合条件但是没有数据,那么就显示null,很明显,可以用ifnull或者case when

在使用case when的时候,当符合store1的时,同列其他两行数据为null,但group by只能一行一列,那么怎么合成一列一行呢?

使用聚合函数,可以使用sum,也可以使用max,将多行数据合并为一行。

 

group by,顾名思义,根据某个条件进行分组,符合那个条件的数据都在同一个组里边,那么怎么筛选出来这个组里我想要的那条数据 或者 我想要的这个组的汇总数据呢?使用having进行条件限定 或者 聚合函数。

不理解这道题目的小伙伴可以去看一下sql查询语句的执行顺序,也可以看一下这一篇文章

https://blog.csdn.net/shaofei63/article/details/42800793

知识点:sql行转列,聚合函数,group by,case...when...,ifnull,子查询

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值