在查询中使用下一个NOT NULL值覆盖NULL结果

时间:2016-04-25 11:02:38

标签: sql postgresql join

我有两张桌子:

t1

t1.id | t1.val   
----- | ------  
    1 |   a  
    2 |   b  
    3 |   c  
    4 |   d  
    5 |   e  
    6 |   f  
    7 |   j

t2

t2.id|t2.val   
---- | ---  
    1| www  
    3| xxx  
    6| yyy  
    7| zzz  

当我应用这样的sql-instruction时:

SELECT t1.id, t1.val, t2.val
FROM t1
LEFT JOIN t2 ON ( t1.id = t2.id )

结果给出了相同的表格

t1.id | t1.val | t2.val   
----- | ------ | ------  
    1 | a | www  
    2 | b | NULL  
    3 | c | xxx  
    4 | d | NULL  
    5 | e | NULL  
    6 | f | yyy  
    7 | j | zzz  

如果我想得到像这样的结果,请帮我改变sql-instruction

t1.id | t1.val | t2.val   
----- | ------ | ------  
    1 | a | www  
    2 | b | xxx  
    3 | c | xxx  
    4 | d | yyy  
    5 | e | yyy  
    6 | f | yyy  
    7 | j | zzz  

谢谢大家!!

2 个答案:

答案 0 :(得分:0)

一种方法使用相关子查询:

select t1.*,
       (select t2.val
        from t2
        where t2.id >= t1.id
        order by t2.id
        limit 1
       ) as t2val
from t1;

另一种方法使用窗口函数,但它有点复杂:

SELECT t1.id, t1.val, t2.val
FROM (SELECT t1.id, t1.val,
             MIN(t2.id) OVER (ORDER BY id DESC) as matching_id
      FROM t1 LEFT JOIN
           t2
           ON t1.id = t2.id
     ) t LEFT JOIN
     t2
     ON t2.id = t.matching_id;

答案 1 :(得分:0)

SELECT t1.id,t1.val,NVL(t2.val,LEAD(t2.val)OVER(ORDER BY t2.id)) 从t1 LEFT JOIN t2 ON(t1.id = t2.id)