【发布时间】:2026-01-30 09:45:01
【问题描述】:
下面的 SQL 允许我查看我手动输入到 @report_date 的指定日期的活动订阅。相反,我想显示过去两年我们的活跃订阅者的图表,因此我希望能够在过去 2 年中的每一天进行分组。但是,我不确定如何让@report_date 在过去一年中的每一天都循环播放。
不幸的是,取消表背后的逻辑值得怀疑。每次客户重新激活他们的订阅时,取消行都会更新以将“重新激活”设置为 1。如果客户第二次取消取消表中的新行,“重新激活”设置为默认值 0。因此,找到在@report_date 被取消的人,“重新激活”必须设置为 0,或者如果他们已经重新激活,那么他们的重新激活日期必须在 @report_date 之后。
set @report_date = '2020-06-11';
SELECT
@report_date AS Date,
COUNT(DISTINCT s.customer_id) AS 'Active Subscribers'
FROM
subscriptions AS s
WHERE
(authorized = 1 OR authorized = 0)
AND s.created_date < @report_date
AND s.customer_id NOT IN (SELECT customer_id
FROM cancellations
WHERE (reactivated = 0 OR reactivated_date > @report_date)
AND cancellation_date < @report_date);
订阅表:
customer_id | created_date | authorized
1 2020-06-06 1
2 2020-06-07 1
3 2020-06-08 -1
4 2020-06-08 1
取消表:
customer_id | cancellation_date | reactivated | reactivation_date
1 2020-06-09 1 2020-06-10
2 2020-06-12 0 NULL
4 2020-06-10 1 2020-06-12
电流输出:
Date | Active Subscribers
2020-06-11 1
期望的结果:
Date | Active Subscribers
2020-06-12 2
2020-06-11 1
2020-06-10 1
etc.
【问题讨论】:
-
这个数据看起来真的很乱。如果订阅者多次重新激活会怎样?
-
@GordonLinoff 我完全同意。在我开始在这里工作之前,该数据库是由一家外包机构建立的。如果订阅者第二次重新激活,则第二个取消行中的“重新激活”字段设置为 1。
-
您应该提供更清晰的数据来处理这些情况。
-
@GordonLinoff 你到底是什么意思?我已经尽可能地简化了数据。
标签: mysql sql date count window-functions