分解并计算2个日期栏中的所有项目

时间:2019-04-23 06:10:58

标签: sql date count

我想获取所有可能的日期(在这种情况下为event_day)以及在start_date和end_date之间发生的事件数。请查看下表

 ---------------------------------
 start_date |  end_date   |  event
 ---------------------------------
 2019-01-01 |  2019-01-04 | A 
 2019-01-02 |  2019-01-03 | B
 2019-01-01 |  2019-01-06 | C

,我想查询所有日期的event_count数量。请查看以下结果

----------------------------
event_day |  event_count
----------------------------
2019-01-01 |   2
2019-01-02 |   3
2019-01-03 |   3
2019-01-04 |   2
2019-01-05 |   1
2019-01-06 |   1

我阅读了其他资料,但只能找到如何从2个日期中爆炸日期。有什么帮助吗?谢谢

3 个答案:

答案 0 :(得分:1)

您可以使用demo on dbfiddle.uk来解决此问题:

SELECT date_value AS event_day, COUNT(*) AS event_count
FROM (
    SELECT ADDDATE('1970-01-01', t4 * 10000 + t3 * 1000 + t2 * 100 + t1 * 10 + t0) AS date_value
    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
) calendar INNER JOIN events ON calendar.date_value BETWEEN events.start_date AND events.end_date
WHERE calendar.date_value BETWEEN '2019-01-01' AND '2019-01-04' -- to filter for a specific date range.
GROUP BY date_value

{{3}}

答案 1 :(得分:0)

如果您使用的是postgres,则可以使用generate_series生成日历表,基本上,您需要一个日历表才能分解日期。

WITH a AS(
  Select '2019-01-01'::date as start_date  ,'2019-01-04'::date as  end_date union all
  Select '2019-01-02'::date , '2019-01-03'::date union all
  Select '2019-01-01'::date, '2019-01-06'::date 
  )
 Select t.date_generated,count(*) as event
 from a
 JOIN(Select date_generated
  from generate_series(date '2019-01-01',
                   date '2019-12-31',
                   interval '1 day') as t(date_generated)
   ) t
   ON t.date_generated between a.start_date and a.end_date
   group by t.date_generated
   order by t.date_generated

答案 2 :(得分:0)

 select Calendar.Calndr_date , count(Calendar.Calndr_date) count_events
 from event_table
 join Calendar on
 Calendar.Calndr_date between  event_table.start_date and event_table.end_date
 group by Calendar.Calndr_date 

请讨论是否有任何问题。 请创建日历表并插入日历数据。enter image description here