我需要建立一种基于桌子的som历史 id和日期
每个日期都标志着一个变化和最新的日期 活跃的,
table
historic_trans
id trans_date
22 20170510
22 20170502
22 20170412
我想建立一个最新行的历史表 通过添加过期列作为' 99991231'
来获得活跃标记我可以通过
轻松找到活跃的select id, max(trans_date)trans_date, '99991231' as Expiredate, 'yes' as active
from historic_trans
where id = '22'
group by id
但我真的需要在前一行设置trans_date 在我的非活动行
id trans_date Expiredate active
22 20170510 99991231 yes
22 20170502 20170510 no
22 20170412 20170502 no
因此expiredate反映了交易的变化
可以在纯hql / sql
中完成我一直在玩以下代码,但我被困在其中
select historic_trans.id, historic_trans.trans_date,
case when aktiv.Expiredate = '99991231' then aktiv.Expiredate
else aktiv.Expiredate
end as Expiredate
from historic_trans
left outer join
(
select id, max(trans_date)trans_date, '99991231' as Expiredate, 'yes' as active
from historic_trans
where id = '22'
group by id
) aktiv on aktiv.id = historic_trans.id and aktiv.trans_date = historic_trans.trans_date
where historic_trans.id = '22'
有什么建议吗?
答案 0 :(得分:1)
select id
,trans_date
,lag (trans_date,1,date '9999-12-31') over w as Expiredate
,case when row_number () over w = 1 then 'yes' else 'no' end as active
from historic_trans
window w as (partition by id order by trans_date desc)
;
+----+------------+------------+--------+
| id | trans_date | expiredate | active |
+----+------------+------------+--------+
| 22 | 2017-05-10 | 9999-12-31 | yes |
| 22 | 2017-05-02 | 2017-05-10 | no |
| 22 | 2017-04-12 | 2017-05-02 | no |
+----+------------+------------+--------+