如果键组合为null,则填充先前的值;如果没有值,则填充null

时间:2018-09-25 04:09:19

标签: sql teradata

输入

key1 key 2 date
A    B     1/1/2018
A    B      NULL
A    C     2/2/2018
A    C      NULL
A   A       NULL

输出:

key 1 key 2   date
A    B     1/1/2018
A    B      1/1/2018
A    C     2/2/2018
A    C      2/2/2018
A   A       NULL

3 个答案:

答案 0 :(得分:2)

使用last_value用先前存在的值填充NULL很简单:

select key1,key2,
   LAST_VALUE(date IGNORE NULLS)
   OVER (ORDER BY key1,key2) 
from mytab

您可能想对每个key1执行此操作:

select key1,key2,
   LAST_VALUE(date IGNORE NULLS)
   OVER (PARTITION BY key1
         ORDER BY key2) 
from mytab

编辑:根据您的示例数据,key1key2相同,在这种情况下可能是

select key1,key2,
   MAX(date)
   OVER (PARTITION BY key1, key2) 
from mytab

答案 1 :(得分:0)

您需要创建一个获得最大值的子查询,假设您的 previous 是组合键的最大日期:

select key1,key2,coalesce(date,maxdate) as date
from mytab
join(
    select key1,key2,max(date) as maxdate 
    from mytab 
    group by key1,key2
    ) m on m.key1=mytab.key1 and m.key2=m.key2

答案 2 :(得分:0)

这里...

-----------------------------Create dummy table----------------------------------
DECLARE @MyTable TABLE
(
    [key_1]    VARCHAR(100) NULL,
    [key_2]    VARCHAR(100) NULL,
    [date]     DATE NULL 
);

-----------------------------Insert dummy data----------------------------------
INSERT  @MyTable ([key_1], [key_2], [date])
SELECT 'A', 'B', '1/1/2018' UNION ALL
SELECT 'A', 'B', NULL UNION ALL
SELECT 'A', 'C', '2/2/2018' UNION ALL
SELECT 'A', 'C', NULL UNION ALL
SELECT 'A', 'A', NULL  ;

-----------------------------Update table--------------------------------------
UPDATE MT_1 
SET MT_1.[date] = 
    (SELECT MAX(MT_2.date) 
    FROM @MyTable AS MT_2 
    WHERE MT_1.key_1 = MT_2.key_1 AND MT_1.key_2 = MT_2.key_2) 
FROM @MyTable AS MT_1

------------------------------Output Result------------------------------------
SELECT * FROM @MyTable