将 Oracle Decode 转换为 Postgres Case 表达式
Convert Oracle Decode to Postgres Case expression
我们有一个现有的 Oracle SQL 查询需要转换为 Postgres。解码对我来说很复杂,希望在转换为 Postgres CASE 方面获得一些帮助。
现有SQL:
SELECT P.t_id p_t_id,
Q.t_id q_t_id
FROM pts Q,
pts P
WHERE P.t_id <> Q.t_id
AND ((decode(substr(P.c_num,2,1),
'0', 1,
'1', 1,
'2', 1,
'3', 1,
'4', 1,
'5', 1,
'6', 1,
'7', 1,
'8', 1,
'9', 1,
0) != 0
AND P.c_num IS NOT NULL
...rest of query...
谢谢
在 Postgres 中,我会将查询表述为:
select p.t_id p_t_id, q.t_id q_t_id
from pts q
inner join pts p on p.t_id <> q.t_id
where p.c_num ~ '^.\d'
理由:
- 基本上
decode()
语句检查字符串 p.c_num
的第二个字符是否为数字。这看起来比它需要的更复杂(在 Oracle 中和在 Postgres 中一样)。我发现为此使用正则表达式更简单 - '^.\d'
表示:字符串的开头 (^
),然后是任何字符 (.
),然后是数字 (\d
).你也可以使用 in
:
substr(p.c_num, 1, 2) in ('0', '1', '2', ..., '9')
p.c_num
上的 not null
条件是不必要的 - null
值不匹配任何正则表达式(在 Oracle 中,它们将传递 decode()
要么测试)
使用标准联接(使用 on
关键字),而不是 old-school 隐式联接(在 from
子句中使用逗号)
我们有一个现有的 Oracle SQL 查询需要转换为 Postgres。解码对我来说很复杂,希望在转换为 Postgres CASE 方面获得一些帮助。
现有SQL:
SELECT P.t_id p_t_id,
Q.t_id q_t_id
FROM pts Q,
pts P
WHERE P.t_id <> Q.t_id
AND ((decode(substr(P.c_num,2,1),
'0', 1,
'1', 1,
'2', 1,
'3', 1,
'4', 1,
'5', 1,
'6', 1,
'7', 1,
'8', 1,
'9', 1,
0) != 0
AND P.c_num IS NOT NULL
...rest of query...
谢谢
在 Postgres 中,我会将查询表述为:
select p.t_id p_t_id, q.t_id q_t_id
from pts q
inner join pts p on p.t_id <> q.t_id
where p.c_num ~ '^.\d'
理由:
- 基本上
decode()
语句检查字符串p.c_num
的第二个字符是否为数字。这看起来比它需要的更复杂(在 Oracle 中和在 Postgres 中一样)。我发现为此使用正则表达式更简单 -'^.\d'
表示:字符串的开头 (^
),然后是任何字符 (.
),然后是数字 (\d
).你也可以使用in
:
substr(p.c_num, 1, 2) in ('0', '1', '2', ..., '9')
p.c_num
上的not null
条件是不必要的 -null
值不匹配任何正则表达式(在 Oracle 中,它们将传递decode()
要么测试)使用标准联接(使用
on
关键字),而不是 old-school 隐式联接(在from
子句中使用逗号)