SQL - 在一周内获取该周记录的结果计数和从该周起 7 天的记录计数

SQL - In a week get result count of records in that week and count of records ageing 7days from that week

这是红移SQL 我试图在一周内获得 2 个结果:

  1. 该周的总记录数
  2. 从该周算起超过 7 天的记录总数。

假设有以下格式的样本 100 条记录,在当前示例 7 records/week:

day         code    week
1/1/2020    P001    1
1/2/2020    P002    1
1/3/2020    P003    1
1/4/2020    P004    1
1/5/2020    P005    2
1/6/2020    P006    2
1/7/2020    P007    2
1/8/2020    P008    2
1/9/2020    P009    2
1/10/2020   P010    2
1/11/2020   P011    2
.....................
4/8/2020    P099    15

尝试获得这样的输出:

Week count count>7 days
1     7     0
2     7     7
3     7     14
4     7     21
15    7     98

基本上最近一周,我正在尝试获取不同数量的超过 7 天的记录。在实际使用情况下,每周的记录数会有所不同。

我尝试过的:

calendar_week_number,
count(code) as count 1,
count(DISTINCT (case when datediff(day, trunc(completion_date-7), '2020-01-01') then code end)) as count 2,
count(case when completion_date between TO_DATE('20200101','YYYYMMDD') and TO_DATE(completion_date,'YYYYMMDD')-7 then code end) as count 3

from rbsrpt.RBS_DAILY_ASIN_PROC_SNPSHT ul
    LEFT JOIN rbsrpt.dim_rbs_time t  ON Trunc(ul.completion_date) = trunc(t.cal_date)

where
mp=1
and calendar_year=2020

group by
calendar_week_number

order by calendar_week_number desc

但我的输出如下:

week    count1  count 2 count 3
51      2866    2866    0
50      3211    3211    0
49      6377    6377    0
48      9013    9013    0
47      5950    5950    0

一个选项使用横向连接。首先按周聚合日历 table,然后在数据集中每周执行搜索可能更有效。

假设 Postgres(因为 MySQL 中没有 TO_DATE()):

select d.cal_date, c1.*, c2.*
from (
    select calendar_week_number, min(cal_date) as cal_date
    rbsrpt.dim_rbs_time t
    group by calendar_week_number
) t
cross join lateral (
    select count(*) as cnt
    from rbsrpt.rbs_daily_asin_proc_snpsht r
    where r.completion_date >= t.cal_date
      and r.completion_date <  t.cal_date + interval '7 day'
) c1
cross join lateral (
    select count(*) as cnt_aged
    from rbsrpt.rbs_daily_asin_proc_snpsht r
    where r.completion_date >= t.cal_date - interval '7' day
      and r.completion_date <  t.cal_date
) c2

这会在 7 天后过时记录。如果您想要 30 天,您可以更改第二个子查询的 where 子句:

cross join lateral (
    select count(*) as cnt_aged
    from rbsrpt.rbs_daily_asin_proc_snpsht r
    where r.completion_date >= t.cal_date - interval '30 day'
      and r.completion_date <  t.cal_date - interval '23 day'
) c2

编辑:如果你的数据库不支持横向连接,你可以使用子查询代替:

select d.cal_date, 
    (
        select count(*) 
        from rbsrpt.rbs_daily_asin_proc_snpsht r
        where r.completion_date >= t.cal_date
          and r.completion_date <  t.cal_date + interval '7 day'
    ) as cnt,
    (
        select count(*) 
        from rbsrpt.rbs_daily_asin_proc_snpsht r
        where r.completion_date >= t.cal_date - interval '7' day
          and r.completion_date <  t.cal_date
    ) as cnt_aged
from (
    select calendar_week_number, min(cal_date) as cal_date
    rbsrpt.dim_rbs_time t
    group by calendar_week_number
) t