使用多列“排序依据”条件按顺序对结果进行排序和编号

时间:2020-05-13 00:56:47

标签: sql oracle sql-order-by

全部

我一直在尝试使用以下结构的数据:

╔══════════════╦═══════════╦══╗
║ Alphabetical ║ Numerical ║  ║
╠══════════════╬═══════════╬══╣
║ A            ║        15 ║  ║
║ A            ║        30 ║  ║
║ E            ║       100 ║  ║
║ C            ║        45 ║  ║
║ F            ║        25 ║  ║
║ C            ║        65 ║  ║
║ B            ║        25 ║  ║
║ F            ║        35 ║  ║
║ C            ║       100 ║  ║
║ A            ║        10 ║  ║
║ C            ║        20 ║  ║
║ B            ║         5 ║  ║
║ E            ║        10 ║  ║
║ F            ║        85 ║  ║
║ D            ║        30 ║  ║
║ F            ║         1 ║  ║
╚══════════════╩═══════════╩══╝

要获得以下内容:

╔══════════════╦══════╦═════════╗
║ Alphabetical ║ Rank ║ Numeric ║
╠══════════════╬══════╬═════════╣
║ A            ║    1 ║      30 ║
║ A            ║    2 ║      15 ║
║ A            ║    3 ║      10 ║
║ B            ║    1 ║      25 ║
║ B            ║    2 ║       5 ║
║ C            ║    1 ║     100 ║
║ C            ║    2 ║      65 ║
║ C            ║    3 ║      45 ║
║ C            ║    4 ║      20 ║
║ D            ║    1 ║      30 ║
║ E            ║    1 ║     100 ║
║ E            ║    2 ║      10 ║
║ F            ║    1 ║      85 ║
║ F            ║    2 ║      35 ║
║ F            ║    3 ║      25 ║
║ F            ║    4 ║       1 ║
╚══════════════╩══════╩═════════╝

基本上,要按字母顺序对字段进行升序排序,请按降序对数字字段进行排序,并使用用于数字字段的顺序(按字母字段分组)来获取顺序或等级。

只有在我按字母顺序列将其限制为一个特定值的情况下,我才能实现该目标,方法是:

select ordered_src.*, ROWNUM Rank from (select src.* from Source src where alphabetical = 'A' order by Numeric desc) ordered_src;

但是我不知道如何获得上面显示的结果。任何想法?另外,有没有其他选择也可以在mysql / mssql / etc中使用?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用row_number()

select s.*,
       row_number() over (partition by alphabetical order by numerical desc) as rank
from source s
order by alphabetical, rank;