SQL 从解码切换到大小写

SQL switch from decode to case

我有一个执行类似操作的查询...

SELECT * FROM ...
...
ORDER BY DECODE(APR(ACC.RATE,'X'), 'FIRST RATE', 1, 'SECOND RATE', 2, 3);

因为我正在处理 h2 数据库并且 h2 没有解码和解码别名很难实现所以我想知道是否可以将此 DECODE 转换为 CASE 语句。如何转换?

解码意味着:

CASE FirstParam
  WHEN SecondParam THEN ThirdParam 
  WHEN FourthParam THEN FifthParam
  WHEN SixthParam THEN Seventh... etcetera
  ELSE LastParam -- If number of params is odd, otherwise ELSE NULL is implied
END

所以

CASE APR(ACC.RATE,'X')
  WHEN 'FIRST RATE' THEN 1
  WHEN 'SECOND RATE' THEN 2
  ELSE 3
END

ORDER BY DECODE(APR(ACC.RATE,'X'), 'FIRST RATE', 1, 'SECOND RATE', 2, 3);

您的 ORDER BY 子句有问题。每当 DECODE 使用 default value 时,排序将 无法保证 。对于值 FIRST RATESECOND RATE,您的查询只有 的正确顺序,对于这两个值以外的值,将永远不会保证顺序。

是这样的:

FIRST RATE - 1
SECOND RATE - 2
Anything else - 3

因此,现在指定排序为 value 3 的所有值将在 随机 .

更好的方法是:

ORDER BY DECODE(APR(ACC.RATE,'X'), 'FIRST RATE', 1, 'SECOND RATE', 2, 3), APR(ACC.RATE,'X')

现在,所有行都保证始终处于特定的顺序

使用 CASE 表达式:

ORDER BY
CASE (APR(ACC.RATE,'X')
WHEN 'FIRST RATE' THEN
  1
WHEN 'SECOND RATE' THEN
  2
ELSE
  3
END, APR(ACC.RATE,'X')

一个有效的例子:

SQL> WITH DATA(id) AS(
  2  SELECT 'X' FROM dual UNION ALL
  3  SELECT 'A' FROM dual UNION ALL
  4  SELECT 'Z' FROM dual UNION ALL
  5  SELECT 'M' FROM dual UNION ALL
  6  SELECT 'I' FROM dual UNION ALL
  7  SELECT 'N' FROM dual
  8  )
  9  SELECT * FROM DATA
 10  ORDER BY
 11  CASE id
 12  WHEN 'M' THEN
 13    1
 14  WHEN 'I' THEN
 15    2
 16  WHEN 'N' THEN
 17    3
 18  ELSE
 19    4
 20  END, id
 21  /

I
-
M
I
N
A
X
Z

6 rows selected.

SQL>