0
点赞
收藏
分享

微信扫一扫

leetcode简单之1795.每个产品在不同商店的价格

我是小小懒 2022-04-05 阅读 238
mysql

表:Products

Column NameType
product_idint
store1int
store2int
store3int

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

问题

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

示例

输入:

Products table:

product_idstore1store2store3
095100105
170null80

输出:

product_idstoreprice
0store195
0store2100
0store3105
1store170
1store380

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

解答

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

tips

核心点1:

列转行——用到UNION ALL
如果是行转列——用到CASE WHEN

核心点2:UNION ALL和UNION区别

UNION ALL:对两个结果集进行并集操作,包括重复行;
UNION:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序

举报

相关推荐

0 条评论