力扣-每个产品在不同商店的价格

大家好,我是空空star,本篇带大家了解一道简单的力扣sql练习题。


前言


一、题目:1795. 每个产品在不同商店的价格

表:Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store1      | int     |
| store2      | int     |
| store3      | int     |
+-------------+---------+

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

请你重构 Products 表,查询每个产品在不同商店的价格,使得输出的格式变为(product_id, store, price) 。如果这一产品在商店里没有出售,则不输出这一行。
输出结果表中的 顺序不作要求 。
查询输出格式请参考下面示例。

输入:
Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0          | 95     | 100    | 105    |
| 1          | 70     | null   | 80     |
+------------+--------+--------+--------+
输出:
+------------+--------+-------+
| product_id | store  | price |
+------------+--------+-------+
| 0          | store1 | 95    |
| 0          | store2 | 100   |
| 0          | store3 | 105   |
| 1          | store1 | 70    |
| 1          | store3 | 80    |
+------------+--------+-------+

解释:
产品0在store1,store2,store3的价格分别为95,100,105。
产品1在store1,store3的价格分别为70,80。在store2无法买到。

二、解题

1.正确示范①

提交SQL

select product_id,store,price from(
    select product_id,'store1' store,
    store1 price
    from Products
    union all
    select product_id,'store2' store,
    store2 price
    from Products
    union all
    select product_id,'store3' store,
    store3 price
    from Products
) u 
where price is not null;

运行结果

2.正确示范②

提交SQL

select product_id,'store1' store,
store1 price
from Products
where store1 is not null
union all
select product_id,'store2' store,
store2 price
from Products
where store2 is not null
union all
select product_id,'store3' store,
store3 price
from Products
where store3 is not null;

运行结果

3.正确示范③

提交SQL

select product_id,'store1' store,
store1 price
from Products
where store1 is not null
union
select product_id,'store2' store,
store2 price
from Products
where store2 is not null
union
select product_id,'store3' store,
store3 price
from Products
where store3 is not null;

运行结果

4.正确示范④

提交SQL

select product_id,store,price from(
    select product_id,'store1' store,
    store1 price
    from Products
    union
    select product_id,'store2' store,
    store2 price
    from Products
    union
    select product_id,'store3' store,
    store3 price
    from Products
) u 
where price is not null;

运行结果

5.其他


总结

列转行用union或者union all,本题产品id是主键,所以不会存在重复的,那么union和union all都可以。
union会去重,union all不会,union all效率高于union

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空空star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值