嵌套 sql 排序
nested sql sorting
我有如下三个字段:
f1 f2 f3
b x 100.22
c y 150.15
a x 240.35
a y 130.25
b y 789.34
c x 199.89
我想这样排序:
f1 f2 f3
b y 789.34
b x 100.22
a x 240.35
a y 130.25
c x 199.89
c y 150.15
主要排序应该是按照f3进行的,所以f3中和值较大的一组f1值应该在上(降序)。
此外,f3 的值应该在它们自己的组中降序排列。
您可以使用子查询计算总和,然后将其用于 order by
:
select f1, f2, f3
from (select t.*, sum(f3) over (partition by f1) as sumf1
from table t
) t
order by sumf1 desc, f1, f3 desc;
实际上,您不需要子查询(尽管我更喜欢将它们与 window 函数一起使用):
select f1, f2, f3
from table t
order by sum(f3) over (partition by f1) desc, f1, f3 desc;
我有如下三个字段:
f1 f2 f3
b x 100.22
c y 150.15
a x 240.35
a y 130.25
b y 789.34
c x 199.89
我想这样排序:
f1 f2 f3
b y 789.34
b x 100.22
a x 240.35
a y 130.25
c x 199.89
c y 150.15
主要排序应该是按照f3进行的,所以f3中和值较大的一组f1值应该在上(降序)。 此外,f3 的值应该在它们自己的组中降序排列。
您可以使用子查询计算总和,然后将其用于 order by
:
select f1, f2, f3
from (select t.*, sum(f3) over (partition by f1) as sumf1
from table t
) t
order by sumf1 desc, f1, f3 desc;
实际上,您不需要子查询(尽管我更喜欢将它们与 window 函数一起使用):
select f1, f2, f3
from table t
order by sum(f3) over (partition by f1) desc, f1, f3 desc;