【发布时间】:2017-06-20 06:48:15
【问题描述】:
我有一个示例数据如下,想得到一个想要的 o/p,请帮我出主意。
我希望第 3、4 行 prev_diff_value 的 o/p 为 2015-01-01 00:00:00 而不是 2015-01-02 00:00: 00.
with dat as (
select 1 as id,'20150101 02:02:50'::timestamp as dt union all
select 1,'20150101 03:02:50'::timestamp union all
select 1,'20150101 04:02:50'::timestamp union all
select 1,'20150102 02:02:50'::timestamp union all
select 1,'20150102 02:02:50'::timestamp union all
select 1,'20150102 02:02:51'::timestamp union all
select 1,'20150103 02:02:50'::timestamp union all
select 2,'20150101 02:02:50'::timestamp union all
select 2,'20150101 03:02:50'::timestamp union all
select 2,'20150101 04:02:50'::timestamp union all
select 2,'20150102 02:02:50'::timestamp union all
select 1,'20150104 02:02:50'::timestamp
)-- select * from dat
select id , dt , lag(trunc(dt)) over(partition by id order by dt asc) prev_diff_value
from dat
order by id,dt desc
O/P :
id dt prev_diff_value
1 2015-01-04 02:02:50 2015-01-03 00:00:00
1 2015-01-03 02:02:50 2015-01-02 00:00:00
1 2015-01-02 02:02:51 2015-01-02 00:00:00
1 2015-01-02 02:02:50 2015-01-02 00:00:00
1 2015-01-02 02:02:50 2015-01-01 00:00:00
【问题讨论】:
-
您好,您能否更好地解释一下您希望在 prev_diff_value 列中看到的内容? lag 函数将前一个函数作为参考,因此它工作正常,您要求该 ro 红移。为什么要退一步?也许您可以按年-月-日 hh-mm 分组忽略秒数,因此 2015-01-02 02:02:50 和 2015-01-02 02:02:51 将被视为相同?
-
好的..我知道它返回了正确的结果,但是我期望的 prev-diff-value 中的值是前一天或者可能是前一天而不是前一行
标签: sql amazon-redshift lag