Redshift SQL 过去 n 天的事件数

Redshift SQL number of events in past n days

我在红移中有一个 SQL table,看起来像:

ID Date Gender
A 2019-02-01 M
B 2019-02-01 M
A 2019-01-01 M
C 2019-03-01 F
B 2019-03-01 M
C 2019-02-01 F
A 2019-09-01 M

我想创建一个列,为该特定 ID 提供过去 60 天内的先前记录数。每个 ID 的第一条记录(按日期)的计数应该为 0,因为在该记录之前没有记录。此外,输入 table 不是按 ID 或日期 grouped/sorted。

对于此 table,预期输出为:

ID Date Gender Number_in_past60
A 2019-02-01 M 1
B 2019-02-01 M 0
A 2019-01-01 M 0
C 2019-03-01 F 1
B 2019-03-01 M 1
C 2019-02-01 F 0
A 2019-09-01 M 0

输出 table 中的行不必与输入 table 的顺序相同。只要新的 count 列正确,任何 order/grouping 都可以。

速度不是很快,但应该可以了

select 
  t_ext.*, 
  (
    select count(*) 
    from _table as t_int 
    where t_int."ID" = t_ext."ID"
    and t_int."Date" between t_ext."Date" - 60 and t_ext."Date" - 1
  ) as "Number_in_past60"
from _table as t_ext;

大方向可能看起来像那样,尽管我猜它可能需要对真实数据进行一些调整

with dates as (
    select date, id
    from mytable
),
grouped as (
    select
        t.id, count(*) cnt_past60_days
    from mytable t
        join dates d on t.id = d.id 
                         and date_diff('day', t.date, d.date) between -60 and 0
    group by 1
)
select t1.*, g.cnt_past60_days
from mytable t1
    left join grouped g on t1.id = g.id and t1.createddate = g.date