高级农民
- 积分
- 4195
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-1-22
- 最后登录
- 1970-1-1
|
2253. Dynamic Unpivoting of a Table
Attempted
Hard
Topics
SQL Schema
0
Table: Products
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| store_name1 | int |
| store_name2 | int |
| : | int |
| : | int |
| : | int |
| store_namen | int |
+-------------+---------+
product_id is the primary key for this table.
Each row in this table indicates the product's price in n different stores.
If the product is not available in a store, the price will be null in that store's column.
The names of the stores may change from one testcase to another. There will be at least 1 store and at most 30 stores.
Important note: This problem targets those who have a good experience with SQL. If you are a beginner, we recommend that you skip it for now.
Implement the procedure UnpivotProducts to reorganize the Products table so that each row has the id of one product, the name of a store where it is sold, and its price in that store. If a product is not available in a store, do not include a row with that product_id and store combination in the result table. There should be three columns: product_id, store, and price.
The procedure should return the table after reorganizing it.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Products table:
+------------+----------+--------+------+------+
| product_id | LC_Store | Nozama | Shop | Souq |
+------------+----------+--------+------+------+
| 1 | 100 | null | 110 | null |
| 2 | null | 200 | null | 190 |
| 3 | null | null | 1000 | 1900 |
+------------+----------+--------+------+------+
Output:
+------------+----------+-------+
| product_id | store | price |
+------------+----------+-------+
| 1 | LC_Store | 100 |
| 1 | Shop | 110 |
| 2 | Nozama | 200 |
| 2 | Souq | 190 |
| 3 | Shop | 1000 |
| 3 | Souq | 1900 |
+------------+----------+-------+
Explanation:
Product 1 is sold in LC_Store and Shop with prices of 100 and 110 respectively.
Product 2 is sold in Nozama and Souq with prices of 200 and 190.
Product 3 is sold in Shop and Souq with prices of 1000 and 1900.
2253. 动态逆透视(Unpivot)中文讲解
题目在做什么
Products 表是宽表:每个商店一列,单元格里是价格。题目要把它转成长表,每行只有 product_id、store、price 三列,价格为 NULL(该商店不卖)的组合不输出。
难点是商店列的名字和数量每个测试用例都不一样(1 到 30 个)。所以不能把列名写死,必须根据表结构动态生成 SQL。
如果列名固定,怎么写
固定为 LC_Store、Nozama、Shop、Souq 时,写法是每列一个 SELECT,再用 UNION ALL 拼起来:
sql
SELECT product_id, 'LC_Store' AS store, LC_Store AS price FROM Products WHERE LC_Store IS NOT NULL
UNION ALL
SELECT product_id, 'Nozama' AS store, Nozama AS price FROM Products WHERE Nozama IS NOT NULL
UNION ALL
...
动态版本做的事就是让 MySQL 自己生成这段文字,再执行它。
解法分三步
第一步:取出所有商店列名
sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'Products'
AND COLUMN_NAME <> 'product_id'
INFORMATION_SCHEMA.COLUMNS 是 MySQL 的元数据表,记录了每张表有哪些列。
TABLE_SCHEMA = DATABASE():限定在当前数据库,避免误取到其他库里的同名表。
COLUMN_NAME <> 'product_id':去掉 product_id,剩下的都是商店列。
第二步:为每个商店列拼一条 SELECT,再合并成一整句
sql
CONCAT('SELECT product_id, ''', COLUMN_NAME, ''' AS store, `',
COLUMN_NAME, '` AS price FROM Products WHERE `',
COLUMN_NAME, '` IS NOT NULL')
对列名 Shop,它会生成:
sql
SELECT product_id, 'Shop' AS store, `Shop` AS price FROM Products WHERE `Shop` IS NOT NULL
几个细节:
''' 是在字符串里写一个单引号(单引号要用两个单引号转义)。所以 'Shop' 作为字符串常量出现在 store 列。
反引号 ` 包住列名,防止列名带特殊字符或与关键字冲突。
WHERE ... IS NOT NULL 实现了"不卖就不输出"。
然后用 GROUP_CONCAT(... SEPARATOR ' UNION ALL ') 把每个商店对应的 SELECT 连成一个长字符串,存进用户变量 @sql。
第三步:执行生成的 SQL
sql
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
PREPARE:把字符串编译成预处理语句。
EXECUTE:执行,结果集就是存储过程的返回值。
DEALLOCATE PREPARE:释放资源。
为什么要加 SET SESSION group_concat_max_len = 1000000
GROUP_CONCAT 默认最多只保留 1024 个字符。每个商店的 SELECT 大约 100 个字符,30 个商店就是 3000 多字符,会被悄悄截断,生成的 SQL 就不完整,执行时报语法错误。所以必须先调大这个上限。
为什么用 UNION ALL 而不是 UNION
UNION 会去重,多一步额外开销。这里不同商店的行 store 值不同,本来就不会重复,所以用 UNION ALL 更快。- CREATE PROCEDURE UnpivotProducts()
- BEGIN
- SET SESSION group_concat_max_len = 1000000;
- SELECT GROUP_CONCAT(
- CONCAT('SELECT product_id, ''', COLUMN_NAME, ''' AS store, `',
- COLUMN_NAME, '` AS price FROM Products WHERE `',
- COLUMN_NAME, '` IS NOT NULL')
- SEPARATOR ' UNION ALL ')
- INTO @sql
- FROM INFORMATION_SCHEMA.COLUMNS
- WHERE TABLE_SCHEMA = DATABASE()
- AND TABLE_NAME = 'Products'
- AND COLUMN_NAME <> 'product_id';
- PREPARE stmt FROM @sql;
- EXECUTE stmt;
- DEALLOCATE PREPARE stmt;
- END
复制代码 |
|