【发布时间】:2021-06-15 17:39:02
【问题描述】:
这是我的表格标记
| quiz_1_marks | quiz_2_marks | quiz_3_marks | quiz_4_marks |
|---|---|---|---|
| 86.5 | 90.3 | 69.9 | 43.2 |
| 36.27 | 54.9 | 28.8 | 69.65 |
我想要选择这样的标记
| max1 | max2 | max3 | max4 |
|---|---|---|---|
| 90.3 | 86.5 | 69.9 | 43.2 |
| 69.65 | 54.9 | 36.7 | 28.8 |
【问题讨论】:
-
考虑修改您的架构。
这是我的表格标记
| quiz_1_marks | quiz_2_marks | quiz_3_marks | quiz_4_marks |
|---|---|---|---|
| 86.5 | 90.3 | 69.9 | 43.2 |
| 36.27 | 54.9 | 28.8 | 69.65 |
我想要选择这样的标记
| max1 | max2 | max3 | max4 |
|---|---|---|---|
| 90.3 | 86.5 | 69.9 | 43.2 |
| 69.65 | 54.9 | 36.7 | 28.8 |
【问题讨论】:
使用条件聚合取消透视、排序、透视
select max1, max2, max3, max4
from tbl_marks
cross join lateral (
select
max(case rn when 1 then qm end) max1,
max(case rn when 2 then qm end) max2,
max(case rn when 3 then qm end) max3,
max(case rn when 4 then qm end) max4
from (
select q.m qm, row_number() over(order by q.m desc) rn
from (
select quiz_1_marks union all
select quiz_2_marks union all
select quiz_3_marks union all
select quiz_4_marks
) q(m)
) t
) t;
【讨论】:
rn 和 qm 是子查询计算的列的别名。