边儿上的小人您要嫌碍事儿,可将鼠标放在上头,边上底下有个叉,点一下就收起来了

【笔记】Oracle列转行unpivot&行转列 PIVOT

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)
    )

PIVOT

例子题目

image

用PIVOT直接转换

select * from products --第一步,查哪的数据
PIVOT (
    AVG(price)  --第二步,将哪一列数据作为行
    FOR store IN ('store1'store1, 'store2'store2, 'store3'store3) --哪些数据作为列名
) PT
order by product_id
posted @   DbWong_0918  阅读(511)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示