从同一个表中以不同的顺序对两列进行排序

问题描述 投票:0回答:1

How to get this output from the table above?

我比较新鲜,我需要尽快解决这个问题。我需要一个简单的解决方案并逐行解释。期待快速回复。帮帮我。 (----满足身材特征要求----)\

sql sql-order-by
1个回答
0
投票

嗯,是的 - 如果您是新手,这样的问题可能会“棘手”。您可能知道应该使用某种 order by 子句,但是 - 如何使用?哪里?

您没有指定您使用的数据库。以下示例使用两个子查询(或 CTE,通用表表达式,或多或少相同)并利用 

row_number

分析函数对数据进行“排序”:


    col1
  • 升序,并且
  • col2
  • 按降序排列
    
    
  • 然后将其值用于
join

,以便您匹配适当的值。

样本数据:

SQL> select * from test; COL1 COL2 ---------- ---------- 1 4 3 5 7 9 2 6 3 1

查询:

SQL> with 2 t1 as 3 (select col1, row_number() over (order by col1) rn from test), 4 t2 as 5 (select col2, row_number() over (order by col2 desc) rn from test) 6 select a.col1, b.col2 7 from t1 a join t2 b on a.rn = b.rn 8 order by a.col1; COL1 COL2 ---------- ---------- 1 9 2 6 3 5 3 4 7 1 SQL>

现在您已经了解了
关键字

(分析函数、CTE、子查询、order by、join),您可以进一步探索并尝试编写自己的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.