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

192 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第25天,点击查看活动详情

一、题目

表: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) 。如果这一产品在商店里没有出售,则不输出这一行。

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

查询输出格式请参考下面示例。

示例 1:

输入:

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无法买到。

来源:力扣(LeetCode)

链接:leetcode.cn/problems/re…

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

创建数据表

根据题意创建Products,设置数据类型并设置主键

CREATE TABLE Products(
	product_id INT PRIMARY KEY,
	store1 INT,
	store2 INT, 
	store3 INT
);
INSERT INTO Products VALUES
(0,95,100,105),
(1,70,NULL,80);

这里有一个列转行的问题,需要单独设置每一列,并且由于如果这一产品在商店里没有出售,则值将为null。这里要做对空判断

例如store1

SELECT  product_id,'store1' AS store, store1 AS price FROM Products WHERE store1 IS NOT NULL

同上,后边的store2和store3都如此判断,得到数据集

SELECT product_id,'store2' AS store, store2 AS price FROM Products WHERE store2 IS NOT NULL
SELECT product_id,'store3' AS store, store3 AS price FROM Products WHERE store3 IS NOT NULL

在得到数据集后需要将三个数据集合并,这里使用UNION ALL,之所以用UNION ALL 而不是用UNION是因为前者没有去重。同时再根据product_id做个升序

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
ORDER BY product_id;

image.png

三、测试执行

测试结果

image.png

四、总结

这里难点在于第一次对于这个列转行数据的理解,它的别名操作步骤以及对数据集的合并。