1

您好我正在使用 DB2 sql 填写下表中的一些缺失数据:

Person       House     From           To      
------       -----     ----           --
1            586       2000-04-16     2010-12-03 
2            123       2001-01-01     2012-09-27
2            NULL      NULL           NULL
2            104       2004-01-01     2012-11-24
3            987       1999-12-31     2009-08-01
3            NULL      NULL           NULL

人 2 在哪里住过 3 栋房子,但中间地址不知道在哪里,什么时候。我无法对他们住的房子做任何事情,但我想拿他们以前住的房子,并使用之前的 To 日期替换 NULL From 日期,并使用下一个地址信息并使用 From 日期替换 null To date 即。

Person       House     From           To      
------       -----     ----           --
1            586       2000-04-16     2010-12-03 
2            123       2001-01-01     2012-09-27
2            NULL      2012-09-27     2004-01-01
2            104       2004-01-01     2012-11-24
3            987       1999-12-31     2009-08-01
3            NULL      2009-08-01     9999-01-01

我了解,如果在空地址之前没有以前的地址,则必须保持为空,但如果空地址是最后一个知道的地址,我想将 To date 更改为 9999-01-01,就像第 3 个人一样。

这种类型的问题在我看来集合论不再是一个好的解决方案,但是我需要找到一个 DB2 解决方案,因为这是我老板使用的!

欢迎任何指示/建议。

谢谢。

4

2 回答 2

2

它可能看起来像这样:

select 
 person,
 house,
 coalesce(from_date, prev_to_date) from_date,
 case when rn = 1 then coalesce (to_date, '9999-01-01')
  else coalesce(to_date, next_from_date) end to_date
from
(select person, house, from_date, to_date,
 lag(to_date) over (partition by person order by from_date nulls last) prev_to_date,
 lead(from_date) over (partition by person order by from_date nulls last) next_from_date,
 row_number() over (partition by person order by from_date desc nulls last) rn
 from temp
) t

以上内容未经测试,但可能会给您一个想法。

我希望在您的实际表中,您有一个列to_datefrom_date它允许您为每个人排序行,否则您将无法对 NULL 日期进行排序,因为您无法知道实际的顺序。

于 2013-06-25T12:04:17.653 回答
1
create table Temp
(
 person varchar(2),
 house int,
 from_date date,
 to_date date 
)

insert into temp values 
(1,586,'2000-04-16','2010-12-03 '),
(2,123,'2001-01-01','2012-09-27'),
(2,NULL,NULL,NULL),
(2,104,'2004-01-01','2012-11-24'),
(3,987,'1999-12-31','2009-08-01'),
(3,NULL,NULL,NULL)


select  A.person,
        A.house,
        isnull(A.from_date,BF.to_date) From_date,
        isnull(A.to_date,isnull(CT.From_date,'9999-01-01')) To_date
from 
((select *,ROW_NUMBER() over (order by (select 0)) rownum from Temp) A left join
 (select *,ROW_NUMBER() over (order by (select 0)) rownum from Temp) BF
 on A.person = BF.person and
 A.rownum = BF.rownum + 1)left join
 (select *,ROW_NUMBER() over (order by (select 0)) rownum from Temp) CT 
  on A.person = CT.person and
  A.rownum = CT.rownum - 1
于 2013-06-25T09:37:19.383 回答