使用DECODE比较多个列并返回单个值

时间:2016-05-19 20:03:49

标签: oracle

我需要Oracle SQL语句的帮助。我需要以各种方式比较3列并返回一个数字。

实施例: A列是空的& B列为空,然后返回C列 B列是NULL& C列为空,然后返回A列 A列是空的& C列为空,然后返回B列 A列是< B栏然后是A栏

依旧等等。

我已经尝试过CASE / WHEN / ELSE和DECODE(当我比较3列时,它很好,因为它们不是NULL或者我得到0。

我找到了COALESCE(NULLIF语句并且效果很好,除了当我有多个值为OVER 0的列时,它总是返回第一个值。我还可以在(或最后)添加“最少”函数NULLIF函数,如果其中2列为NOT NULL,则比较这些2并给出最小值。

期望的结果:

desc      hrs   cyc     days    interval    hrs/cyc/days
============================================================
Task 1    72    0       0       72          hrs  
Task 2    2400  1200    2190    2400        hrs  
Task 3    600   0       180     600         hrs  
Task 4    0     500     120     500         cyc  
Task 5    0     0       30      30          day

在商业智能/网络智能中获得上述结果的编码如下:

= If  ( [Remain Hours]=0  And   [Remain Cycles]  = 0) Then [Schedule Days]  
Else If ([Remain Cycles]=0 And [Remain Days]= 0) Then [Schedule Hours]  
Else If ([Remain Hours]  = 0 And [Remain Days] = 0 ) Then [Schedule Cycles]  
Else If ([Remain Hours]  = 0 And ([Remain Days] < [Remain Cycles]/6 ) ) Then [Schedule Days]  
Else If ([Remain Hours]  = 0 And ( [Remain Cycles]/6 < [Remain Days]   ) ) Then [Schedule Cycles]  
Else If ([Remain Hours]  = 0 And ( [Remain Cycles]/6 > [Remain Days]   ) ) Then [Schedule Days]  
Else If ([Remain Cycles]  = 0 And ([Remain Hours]/13 < [Remain Days] ) ) Then [Schedule Hours]  
Else If ([Remain Cycles]  = 0 And ([Remain Hours]/13 > [Remain Days] ) ) Then [Schedule Days]  
Else If ([Remain Days]  = 0 And ( [Remain Hours]/13 < [Remain Cycles]/6   ) ) Then [Schedule Hours]  
Else If ([Remain Days]  = 0 And ( [Remain Hours]/13 > [Remain Cycles]/6   ) ) Then [Schedule Cycles]  
Else If  ( ([Remain Hours]/13)  < ([Remain Cycles]/6)  And  ( [Remain Hours]/13 < [Remain Days])  )  Then [Schedule Hours]  
Else If ( ([Remain Cycles]/6 < [Remain Days])  And ( [Remain Cycles]/6 < [Remain Hours]/13) ) Then [Schedule Cycles]  
Else If ( ( [Remain Days] < [Remain Cycles]/6 )  And ( [Remain Days] < [Remain Hours]/13) ) Then [Schedule Days]  

1 个答案:

答案 0 :(得分:0)

据我所知,您希望从所有3列中选择最低值,但某些列可以为null,并且列中值的顺序不一定是升序。

假设至少 1列具有非空值,这将适合您:

SELECT LEAST(COALESCE(COL_A, 2147483647), COALESCE(COL_B, 2147483647), COALESCE(COL_C, 2147483647))
FROM YOUR_TABLE

2147483647是PLS_INTEGER的最大可能值。假设您的所有实际值都远远低于此最大值,LEAST函数将返回任何列中的最低值。

如果所有三个列都可以为null,则会出现问题,因为这会为结果返回2147483647。在这种情况下,您可以DECODE忽略该值并返回NULL

SELECT DECODE(LEAST(COALESCE(COL_A, 2147483647), COALESCE(COL_B, 2147483647), COALESCE(COL_C, 2147483647)), 2147483647, NULL)
FROM YOUR_TABLE