如何创建日期序列?

时间:2019-04-22 18:13:09

标签: mysql sql

我想计算数据集中每天的操作次数。

date         action_id
2010-01-01   id00
2010-01-03   id01
2010-01-05   id02

这只是一个示例,但要点是我的数据不包括每天的操作,而我想包括结果中有零个操作的天。

我的计划是这样做。

with dates as (
select [sequence of dates from 2010-01-01 to 2010-02-01] as day)

select day, coalesce(count(distinct action_id), 0) as actions
from dates
left join my_table
on dates.date = my_table.date

如何创建日期序列?

3 个答案:

答案 0 :(得分:3)

您的示例显示了CTE。因此,您可以使用递归CTE:

with recursive dates as (
      select date('2010-01-01') as day
      union all
      select day + interval 1 day
      from dates
      where day < '2010-02-01'
     )
select d.day, count(distinct t.action_id) as actions
from dates d left join
     my_table t
     on d.day = my_table.date
group by d.day;

请注意,COUNT()永远不会返回NULL,因此COALESCE()是不必要的。

在旧版本中,您可以使用日历表或即时生成数据。假设您的表有足够的行:

select d.day, count(distinct t.action_id) as actions
from (select date('2010-01-01') + interval (@rn := @rn + 1) - 1 day as day
  from my_table cross join
       (select @rn := 0) params
  limit 31
 ) d left join
     my_table t
     on d.day = my_table.date
group by d.day;

答案 1 :(得分:0)

似乎您只需要分组并计数

 select date, count(distinct action_id) as action
 from my_table left join
 dates on dates.date = my_table.date
  group by date

答案 2 :(得分:0)

with dates as
(
select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a) ) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as d
) a
where a.Date between '<start_date>' and '<end_date>' )
select day, count(distinct action_id) as actions
from dates
left join my_table
on dates.date = my_table.date