leetcode 1777 每家商店的产品价格(postgresql)

需求

表: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 中没有销售。

输入

在这里插入图片描述

输出

with t1 as (
select product_id,
       case when store='store1' then price end as store1,
       case when store='store2' then price end as store2,
       case when store='store3' then price end as store3
from products
)
select product_id,max(store1) as store1,max(store2) as store2,max(store3) as store3
from t1
group by product_id;

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值