【问题标题】:Order by multiple columns in the SELECT query在 SELECT 查询中按多列排序
【发布时间】:2021-10-13 11:31:48
【问题描述】:

如何在我的选择查询中对结果进行排序以使它们像这样?

1, 1, 0
1, 2, 0
1, 3, 0
1, 1, 1
1, 2, 1
1, 3, 1
2, 1, 0
2, 2, 0
2, 1, 1
2, 2, 1

我尝试了这个查询,但结果不是我想要的:

select * from my_table order by col1, col2, col3

上面例子中col1代表第一个数字,col2是第二个,col3是最后一个数字。

此查询返回:

1, 1, 0
1, 1, 1
1, 2, 0
1, 2, 1
...

谢谢

【问题讨论】:

  • 请用一般语言描述排序顺序。然后你就可以把它翻译成 SQL

标签: sql oracle select


【解决方案1】:

排序应该是1-3-2,我会说。见第 15 行。

SQL> with test (c1, c2, c3) as
  2    (select 2, 1, 0 from dual union all
  3     select 1, 3, 1 from dual union all
  4     select 1, 1, 1 from dual union all
  5     select 1, 1, 0 from dual union all
  6     select 1, 2, 0 from dual union all
  7     select 2, 2, 0 from dual union all
  8     select 2, 2, 1 from dual union all
  9     select 2, 1, 1 from dual union all
 10     select 1, 3, 0 from dual union all
 11     select 1, 2, 1 from dual
 12    )
 13  select *
 14  from test
 15  order by c1, c3, c2;

        C1         C2         C3
---------- ---------- ----------
         1          1          0
         1          2          0
         1          3          0
         1          1          1
         1          2          1
         1          3          1
         2          1          0
         2          2          0
         2          1          1
         2          2          1

10 rows selected.

SQL>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2018-09-04
    • 2018-10-08
    • 2012-07-30
    • 2015-08-12
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多