我有一个这样的表
<表类>
用户
组
价值
tbody><<tr>G1 0.9 G2 0.8 G3 0.3 G4 0.7 BG1 0.9 BG2 0.8 BG3 0.7 CG1 0.9 CG2 0.8 表类>
此操作称为pivot,可通过以下方式执行:
- 使用
ROW_NUMBER
窗口函数 选择每个组的排名 - 为每个新字段 提取组和值
- 聚合每个用户的值
WITH cte AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY user_ ORDER BY VALUE DESC) AS rn
FROM tab
)
SELECT user_,
MAX(CASE WHEN rn = 1 THEN GROUP_ END) AS first_G,
MAX(CASE WHEN rn = 1 THEN VALUE_ END) AS first_G_val,
MAX(CASE WHEN rn = 2 THEN GROUP_ END) AS second_G,
MAX(CASE WHEN rn = 2 THEN VALUE_ END) AS second_G_val,
MAX(CASE WHEN rn = 3 THEN GROUP_ END) AS third_G,
MAX(CASE WHEN rn = 3 THEN VALUE_ END) AS third_G_val
FROM cte
GROUP BY user_