Oracle PL / SQL按情况排序

时间:2019-04-03 01:49:17

标签: oracle sql-order-by

我需要以特定格式排列以下数据

Code    Qty
R   200
R   0
A   100
A   0

必需的输出格式

 Active (A) with stock (Qty > 0)
 Reserve (R) with stock (Qty > 0)
 Active (A) without stock (Qty = 0)
 Reserve (R) without stock  (Qty = 0)

在上述情况下

A 100
R 200
A 0
R 0

请帮助我。我尝试按顺序使用大小写,但最终找不到答案。

2 个答案:

答案 0 :(得分:1)

您尝试ORDER BY CASE是正确的。以下将给出您要寻找的结果:

ORDER BY CASE
           WHEN CODE = 'A' AND QTY > 0 THEN 1
           WHEN CODE = 'R' AND QTY > 0 THEN 2
           WHEN CODE = 'A' AND QTY = 0 THEN 3
           WHEN CODE = 'R' AND QTY = 0 THEN 4
         END;

dbfiddle here

好运。

编辑

要满足OP在注释中提到的其他要求,可以在ORDER BY中添加第二种类型:

ORDER BY CASE
           WHEN CODE = 'A' AND QTY > 0 THEN 1
           WHEN CODE = 'R' AND QTY > 0 THEN 2
           WHEN CODE = 'A' AND QTY = 0 THEN 3
           WHEN CODE = 'R' AND QTY = 0 THEN 4
         END ASC,
         CASE
           WHEN CODE = 'A' AND QTY > 0 THEN QTY
           ELSE NULL
         END DESC;

new dbfiddle here

答案 1 :(得分:0)

对于您提出的特定数据和要求,您实际上并不需要case表达式。 (实际上,我在撒谎-sign()当然是case的一种形式。)

如果您有多于同一行code和正数qtyqty = 0的组合,则存在歧义;与问题陈述完全一样的模糊性。

with
  inputs as (
    select 'R' code, 200 qty from dual union all
    select 'R'     ,   0     from dual union all
    select 'A'     , 100     from dual union all
    select 'A'     ,   0     from dual
  )
select   *
from     inputs
order by sign(qty) desc, code
;

CODE  QTY
---- ----
A     100
R     200
A       0
R       0