【发布时间】:2021-06-18 19:08:06
【问题描述】:
我有一个包含用户 ID、订阅开始日期和订阅结束日期的订阅表。我还有一个带有 dateamp 字段的日历表,即从我的订阅表中的第一个订阅日期开始的每个日期。
我正在尝试写一些东西,它会给我一个包含日期列和三个数字的表格:总活跃人数(当天)、新订阅者数量、退订者数量。
(注意,我尝试使用建议的 GitHub Flavored Markdown 插入示例表,但它只是全部放在一行中。)
目前我正在使用在两个表之间创建多个连接的查询,每个数字一个:
select a.datestamp
,count(distinct case when b_sub.UserID is not null then b_sub.UserID end) as total_w_subscription
,count(distinct case when b_in.UserID is not null then b_in.UserID end) as total_subscribed
,count(distinct case when b_out.UserID is not null then b_out.UserID end) as total_unsubscribed
from Calendar as a
left join Subscription as b_sub -- all those with subscription on given date
on b_sub.sub_dt <= a.datestamp
and (b_sub.unsub_dt > a.datestamp or b_sub.unsub_dt is null)
left join Subscription as b_in -- all those that subscribed on given date
on b_in.sub_dt = a.datestamp
left join Subscription as b_out -- all those that unsubscribed on given date
on b_out.unsub_dt = a.datestamp
where a.datestamp > '2021-06-10'
group by a.datestamp
order by datestamp asc
;
我已为两个表中的日期字段编制索引。如果我只看一天,它会在 3 秒内运行。两天时间已经很漫长了。 Sub 表有超过 260 万条记录,理想情况下,我需要在 2012 年的某个时间开始我的时间表。
什么是最省时的方法?
【问题讨论】:
标签: sql-server date subscription timeline