1795. 每个产品在不同商店的价格 - 力扣(LeetCode)
可以使用 SQL 中的 UNION ALL
来将每个商店的价格展开为行(也就是“行列转换”)。以下是重构 Products
表的 SQL 查询语句:
SELECT product_id, 'store1' AS store, store1 AS price
FROM Products
WHERE store1 IS NOT NULL
UNION ALL
SELECT product_id, 'store2' AS store, store2 AS price
FROM Products
WHERE store2 IS NOT NULL
UNION ALL
SELECT product_id, 'store3' AS store, store3 AS price
FROM Products
WHERE store3 IS NOT NULL;
输出格式示例:
product_id | store | price |
---|---|---|
1 | store1 | 100 |
1 | store3 | 150 |
2 | store2 | 200 |
(仅作为示例,实际输出顺序不限) |
这个查询的核心逻辑是:
-
为每个
store
创建一个SELECT
分支; -
用
UNION ALL
把它们连接起来; -
忽略值为
NULL
的情况(即商品未在该商店出售)。