【发布时间】:2017-05-15 08:58:34
【问题描述】:
我需要根据表构建某种历史记录 带有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
这样过期日期就反映了交易的变化
可以在纯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'
有什么建议吗?
【问题讨论】:
-
有什么理由不使用
date类型或至少ISO 日期格式-yyyy-MM-dd? -
好吧,只要收到数据,我就可以用另一种格式指定 ExpireDate 了。