2012-12-04 26 views
3

我有有具有n列,其中n列名的columns.Some表如下SQL查詢中的表(Oracle)的

c, c2,c3,c4,c5 , c25 

sample data 
c1 c2  c3 c4 c5 (consider only 5 in this case) 
x  y  z z y 
x  y 
x 
a  b  j  k 
a  c  g h i 
k  l  m n o 

現在OP =第二找不到第二不爲空值從右側 樣品運空值以上數據

z 
x 
x (special case as no data left of x) 
j 
h 
n 

不能使用COALESCE廣告,我需要第二NOT NULL不是第一

有人可以幫我這個查詢

回答

3

您可以用更復雜的case語句做到這一點:

select (case when c5 is not null 
      then coalesce(c4, c3, c2, c1) 
      when c4 is not null 
      then coalesce(c3, c2, c1) 
      when c3 is not null 
      then coalesce(c2, c1) 
      else c1 
     end) 
. . . 
+0

謝謝它爲我工作 – user93796

1

喜歡的東西:

select nvl2(c5,c4,nvl2(c4,c3,nvl2(c3,c2,c1))) result 
from my_table 

未經測試。

+0

u能解釋?????????? – user93796

+0

NVL2(expr1,expr2,expr3)函數測試expr1,如果它爲null,則返回expr3,如果不是則返回expr2。 –

+0

+1經測試,它的工作原理... –