gpt4 book ai didi

sql - 如何在Oracle SQL中对同一行的列进行排名

转载 作者:行者123 更新时间:2023-12-02 09:12:08 26 4
gpt4 key购买 nike

我在表中有以下行:

C1 |C2 |C3 |C4

7 | 3 | 1 | 6

我想以这样一种方式构造查询,即为每列指定顺序;
O1 |O2 |O3 |O4
4 | 2 | 1 | 3

是否可以在单个查询中进行这种逐行比较?还是在声明时构造复杂案例的唯一选择?

编辑:我尝试绕过的情况:
case 
when C1 = greatest ( C1, C2, C3, C4) then 1
when C1 >= C2 and C1 >= C3 and C1 < C4
or C1 >= C2 and C1 < C3 and C1 >= C4
or C1 < C2 and C1 >= C3 and C1 >= C4 then 2
when C1 >= C2 and C1 < C3 and C1 < C4
or C1 < C2 and C1 >= C3 and C1 < C4
or C1 < C2 and C1 < C3 and C1 >= C4 then 3
when C1 = least (C1, C2, C3, C4 ) then 4
end as O1

如果值相等,则索引确定顺序:如果C2 = C3,O2 = 1,O2 = 3。

如您所见,这很容易出错。有没有办法使这种比较更加优雅?

比较仅需要在单个行中进行,单个列的顺序不影响表中行的顺序。

编辑2:表中有多行用ID_ROW标识。

最佳答案

复杂的嵌套大小写-不需要时,可以使用“简单”的大小写-当有总和时(虽然有点乏味)

select t.*,

case when c1>c2 then 1 else 0 end
+ case when c1>c3 then 1 else 0 end
+ case when c1>c4 then 1 else 0 end + 1 as q1,

case when c2>c1 then 1 else 0 end
+ case when c2>c3 then 1 else 0 end
+ case when c2>c4 then 1 else 0 end + 1 as q2,

case when c3>c1 then 1 else 0 end
+ case when c3>c2 then 1 else 0 end
+ case when c3>c4 then 1 else 0 end + 1 as q3 ,

case when c4>c1 then 1 else 0 end
+ case when c4>c2 then 1 else 0 end
+ case when c4>c3 then 1 else 0 end + 1 as q4

FROM table1 t;

| c1 | c2 | c3 | c4 | q1 | q2 | q3 | q4 |
|----|----|----|----|----|----|----|----|
| 7 | 3 | 1 | 6 | 4 | 2 | 1 | 3 |
| 6 | 5 | 4 | 1 | 4 | 3 | 2 | 1 |

关于sql - 如何在Oracle SQL中对同一行的列进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com