首页 > 解决方案 > 在 SELECT 查询中按多列排序

问题描述

如何在我的选择查询中订购结果以使它们像这样?

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
...

谢谢

标签: sqloracleselect

解决方案


排序应该是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>

推荐阅读