如何在SELECT中多次消除重复大小写或解码语句?

时间:2011-08-11 22:38:56

标签: sql oracle

例如:

SELECT a,
  IF (c = DECODE(b, "foo1", "bar1", "foo2", "bar2") THEN c ELSE 0),
  IF (d != DECODE(b, "foo1", "bar1", "foo2", "bar2") THEN d ELSE 2),
  IF (e = DECODE(b, "foo1", "bar1", "foo2", "bar2") THEN e ELSE 5)
FROM x

似乎应该采用不那么重复的方式来做这件事......

2 个答案:

答案 0 :(得分:5)

使用

SELECT 
a,
IF (c = b THEN c ELSE 0),
IF (d != b THEN d ELSE 2),
IF (e = b THEN e ELSE 5)
FROM
(SELECT a, DECODE(b, "foo1", "bar1", "foo2", "bar2") b, c, d, e from x);

答案 1 :(得分:2)

SELECT a,
  DECODE( c, b_decoded, c, 0 ),
  DECODE( d, b_decoded, 2, d ),
  DECODE( e, b_decoded, e, 5 )
FROM (SELECT a, c, d, e, DECODE(b, "foo1", "bar1", "foo2", "bar2") b_decoded FROM x)