查找日期范围中的行数-MySQL
我有一个查询,结果如下表所示:查找日期范围中的行数-MySQL,mysql,sql,Mysql,Sql,我有一个查询,结果如下表所示: id accountid amount subs_start subs_end 1 0063r000013Jyz5AAC 0013r00002RTIBEAA5 0.00 2020-11-09 2021-11-09 2 0063r000013KSFaAAO 0014000001boC4CAAU 0.00 2020-11-30 2021-11-30 3 0063r000013KkhK
id accountid amount subs_start subs_end
1 0063r000013Jyz5AAC 0013r00002RTIBEAA5 0.00 2020-11-09 2021-11-09
2 0063r000013KSFaAAO 0014000001boC4CAAU 0.00 2020-11-30 2021-11-30
3 0063r000013KkhKAAS 0014000000YyVs0AAF 0.00 2020-11-30 2021-11-30
4 0063r000013KnHoAAK 0013r00002KHPoMAAX 0.00 2020-11-30 2021-11-30
5 0063r000013KvhlAAC 0011W00002Abn4vQAB 0.00 2020-12-21 2021-12-21
我想编写另一个查询,该查询将导致以下结果:
2020-10-01 0
2020-11-01 4
2020-12-01 5
2021-01-01 5
这个表的第一列应该是我选择的日期范围,第二列是第一个查询中在subs_start和subs_end之间有效的行数。
例如,第一行显示我们有4个帐户id,其子帐户开始和结束时间为2020年11月。您可以使用递归CTE生成所需的日期,然后使用子查询进行计算:
with recursive dates as (
select date('2020-10-01') as dte
union all
select dte + interval 1 month
from dates
where dte < '2021-01-01'
)
select d.dte,
(select count(*)
from t
where t.sub_start <= d.dte and
t.sum_end > d.dte
) as cnt
from dates d
您可以使用递归CTE生成所需的日期,然后使用子查询进行计算:
with recursive dates as (
select date('2020-10-01') as dte
union all
select dte + interval 1 month
from dates
where dte < '2021-01-01'
)
select d.dte,
(select count(*)
from t
where t.sub_start <= d.dte and
t.sum_end > d.dte
) as cnt
from dates d
谢谢它起作用了。对于红移查询,我也需要它,并且在红移中没有定义递归。你知道我该如何用红移键进行查询吗?@Rami。不。在红移中,我建议您创建一个理货表或日期表。谢谢。它起作用了。对于红移查询,我也需要它,并且在红移中没有定义递归。你知道我该如何用红移键进行查询吗?@Rami。不。在红移中,我建议您创建一个理货表或日期表。