【力扣白嫖日记】1795.每个产品在不同商店的价格

前言

练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。

今日题目:

1795.每个产品在不同商店的价格
表:Products

列名类型
product_idint
store1int
store2int
store3int

在 SQL 中,这张表的主键是 product_id(产品Id)。每行存储了这一产品在不同商店 store1, store2, store3 的价格。如果这一产品在商店里没有出售,则值将为 null。

请你重构 Products 表,查询每个产品在不同商店的价格,使得输出的格式变为(product_id, store, price) 。如果这一产品在商店里没有出售,则不输出这一行。

输出结果表中的 顺序不作要求 。


我那不值一提的想法:

  • 首先梳理表内容,题干一共给了一张产品表,记录了产品id,以及产品在不同商店的价格
  • 其次分析需求,需要我们重构数据表,将三列商店数据合并成一列商店数据。
  • 我的想法就是利用union将几个商店的结果连接起来。
select product_id,"store1" as store,store1 as price
from Products 
where store1 is not null
union
select product_id,"store2" as store,store2 as price
from Products
where store2 is not null
union
select product_id,"store3" as store,store3 as price
from Products
where store3 is not null

后面我看了下题解,有专门的总结,一般行转列使用sum(if())+groupby,列转行也就是题干中的要求一般使用union/union all


结果:

在这里插入图片描述


总结:

能运行就行。


  • 19
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值