如何解决SQL - 在一周内获取该周记录的结果计数以及从该周起 7 天的记录计数
这是红移 SQL 我试图在一周内获得 2 个结果:
- 当周的总记录
- 从该周起超过 7 天的总记录。
假设有以下格式的样本 100 条记录,在当前示例中为 7 条记录/周:
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
解决方法
一个选项使用横向连接。先按周聚合日历表,然后在数据集中按周每周执行搜索可能更有效。
假设 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。