力扣之1777.每家商店的产品价格

1. 1777.每家商店的产品价格

1.1 题干

表:Products

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

找出每种产品在各个商店中的价格。

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

返回结果格式如下例所示。

示例 1:

输入:
Products 表:
±------------±-------±------+
| product_id | store | price |
±------------±-------±------+
| 0 | store1 | 95 |
| 0 | store3 | 105 |
| 0 | store2 | 100 |
| 1 | store1 | 70 |
| 1 | store3 | 80 |
±------------±-------±------+
输出:
±------------±-------±-------±-------+
| 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.2 建表

Create table If Not Exists Products (product_id int, store ENUM('store1', 'store2', 'store3'), price int)
Truncate table Products
insert into Products (product_id, store, price) values ('0', 'store1', '95')
insert into Products (product_id, store, price) values ('0', 'store3', '105')
insert into Products (product_id, store, price) values ('0', 'store2', '100')
insert into Products (product_id, store, price) values ('1', 'store1', '70')
insert into Products (product_id, store, price) values ('1', 'store3', '80')

1.3 题解

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;

1.4 结果截图

在这里插入图片描述

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值