需要 oracle 查询 select order by

Need oracle query to select the order by

Table 包含值 1,2,3 但在显示值时需要显示 2,1,3

示例

Table A

    column1      column2   column3
    1            Rat       Animals
    2            Parrot    Bird
    3            Lotus     Flower

需要先显示鹦鹉,再显示鼠和莲花,即 2,1,3

预期输出:

    column1      column2   column3
    2            Parrot    Bird
    1            Rat       Animal
    3            Lotus     Flower

请帮助我按查询顺序解决问题。

请求的订单很奇怪,无论如何都试试这个 -

SELECT Column1,Column2,Column3
FROM TableA
ORDER BY CASE WHEN Column1 = 2 THEN 1 
              WHEN Column1 = 1 THEN 2
              ELSE 3 
         END

您可以在 ORDER BY 子句中针对特定条件使用 CASE 表达式,并让其他行保持其顺序。

设置

SQL> CREATE TABLE t
  2      (column1 int, column2 varchar2(6), column3 varchar2(7));

Table created.

SQL> INSERT ALL
  2      INTO t (column1, column2, column3)
  3           VALUES (1, 'Rat', 'Animals')
  4      INTO t (column1, column2, column3)
  5           VALUES (2, 'Parrot', 'Bird')
  6      INTO t (column1, column2, column3)
  7           VALUES (3, 'Lotus', 'Flower')
  8      INTO t (column1, column2, column3)
  9           VALUES (7, 'def', 'xyz')
 10      INTO t (column1, column2, column3)
 11           VALUES (4, 'abc', 'qwe')
 12  SELECT * FROM dual;

5 rows created.

SQL> COMMIT;

Commit complete.

Table数据

SQL> SELECT * FROM t;

   COLUMN1 COLUMN COLUMN3
---------- ------ -------
         1 Rat    Animals
         2 Parrot Bird
         3 Lotus  Flower
         7 def    xyz
         4 abc    qwe

必填查询

SQL> SELECT * FROM t
  2   ORDER BY
  3    CASE column1
  4       WHEN 1
  5          THEN 2
  6       WHEN 2
  7          THEN 1
  8       ELSE 3
  9    END,
 10   column1;

   COLUMN1 COLUMN COLUMN3
---------- ------ -------
         2 Parrot Bird
         1 Rat    Animals
         3 Lotus  Flower
         4 abc    qwe
         7 def    xyz

SQL>

因此,您有想要的顺序,其他行也保持指定的顺序。