使用以前的记录填写NULLS - Netezza SQL

时间:2015-08-14 21:19:07

标签: sql netezza

我在Aginity Workbench上使用Netezza SQL并拥有以下数据:

id           DATE1              DATE2
1            2013-07-27         NULL
2            NULL               NULL
3            NULL               2013-08-02
4            2013-09-10         2013-09-23
5            2013-12-11         NULL
6            NULL               2013-12-19

我需要在DATE1中填入DATE1字段中填充的前面值的所有NULL值。对于DATE2,我需要执行相同的操作,但顺序相反。所以我想要的输出如下:

id           DATE1              DATE2
1            2013-07-27         2013-08-02
2            2013-07-27         2013-08-02
3            2013-07-27         2013-08-02
4            2013-09-10         2013-09-23
5            2013-12-11         2013-12-19
6            2013-12-11         2013-12-19

我只能读取数据。因此,创建表或视图是不可能的

3 个答案:

答案 0 :(得分:1)

我认为Netezza支持order bymax()的{​​{1}}条款。所以,你可以这样做:

min()

编辑:

在Netezza中,您可以使用select max(date1) over (order by date1) as date1, min(date2) over (order by date2 desc) as date2 . . . last_value()执行此操作:

first_value()

Netezza似乎不支持select last_value(date1 ignore nulls) over (order by id rows between unbounded preceding and 1 preceding) as date1, first_value(date1 ignore nulls) over (order by id rows between 1 following and unbounded following) as date2 上的IGNORE NULL,但它确实支持这些功能。

答案 1 :(得分:0)

我只是在Oracle中对此进行了测试,所以希望它能在Netezza中运行:

<强>小提琴: http://www.sqlfiddle.com/#!4/7533f/1/0

select id,
       coalesce(date1, t1_date1, t2_date1) as date1,
       coalesce(date2, t3_date2, t4_date2) as date2
  from (select t.*,
               t1.date1 as t1_date1,
               t2.date1 as t2_date1,
               t3.date2 as t3_date2,
               t4.date2 as t4_date2,
               row_number() over(partition by t.id order by t.id) as rn
          from tbl t
          left join tbl t1
            on t1.id < t.id
           and t1.date1 is not null
          left join tbl t2
            on t2.id > t.id
           and t2.date1 is not null
          left join tbl t3
            on t3.id < t.id
           and t3.date2 is not null
          left join tbl t4
            on t4.id > t.id
           and t4.date2 is not null
         order by t.id) x
 where rn = 1

答案 2 :(得分:0)

这是一种使用自联接使用最近的最小/最大非空日期填充NULL日期的方法。此查询应适用于大多数数据库

select t1.id, max(t2.date1), min(t3.date2)
from tbl t1
join tbl t2 on t1.id >= t2.id
join tbl t3 on t1.id <= t3.id
group by t1.id

http://www.sqlfiddle.com/#!4/acc997/2