MySQL按时间间隔按天计数记录

时间:2019-01-15 12:21:44

标签: mysql sql

我有一张事件表(现在大约2或3百万个),带有开始和结束日期(分布了几年)。 我想知道每天有多少事件。并非每天开始,而是在每个日历日发生。  例如

| name | start      | End        |
| Ev1  | 2019/01/01 | 2019/01/03 |
| Ev2  | 2019/01/02 | 2019/01/04 |
| Ev3  | 2019/02/22 | 2019/02/23 |

预期结果:

| day        | # |
| 2019/01/01 | 1 |
| 2019/01/02 | 2 |
| 2019/01/03 | 2 |
| 2019/01/04 | 1 |
| 2019/01/05 | 0 |
|     ...    | 0 |
| 2019/02/22 | 1 |
| 2019/02/23 | 1 |

3 个答案:

答案 0 :(得分:1)

为此类信息提供日历表是可行的。然后,

$sql = "SELECT SupplierLotID FROM FactsLot WHERE ID = '$barcodevar'";

答案 1 :(得分:1)

尝试类似的方法,您需要一个日期生成器。

select
    d.dte, count(e.start) as cnt
from 
(
select dte from
    (select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) dte from
    (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
    (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
    (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
    (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
    (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
Where dte between '2019-01-01' and '2020-12-31'
) d
inner join events e
     on e.start <= d.dte and d.dte <= e.end
group by d.dte

答案 2 :(得分:0)

这很棘手。在MySQL中,从日期开始并使用相关的子查询:

select d.dte, count(e.start) as cnt
from (select date('2019-01-01') as dte union all
      select date('2019-01-02') as dte union all
      select date('2019-01-03') as dte union all
      select date('2019-01-04') as dte
     ) d left join
     events e
     on e.start <= d.dte and d.dte <= e.end
group by d.dte
order by d.dte;