【笔记】Oracle列转行unpivot


unpivot
说明:将表中多个列缩减为一个聚合列(多列转多行)
语法:unpivot(新列名 for 聚合列名 in (对应的列名1…列名n ))

写到了一个力扣的题,发现这个unpivot函数还没咋用过

链接:https://leetcode.cn/problems/rearrange-products-table
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

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

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

select
    product_id,lower(store) as store,price
from
    Products
unpivot
    (
        price for store in(store1,store2,store3)
    )

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/279252.html

(0)
上一篇 2022年8月6日
下一篇 2022年8月6日

相关推荐

发表回复

登录后才能评论