简体   繁体   English

确定日期范围内的天数

[英]Identify count of days in a date range

I am very much new to the mysql and sincere apologies as struggling to find the right approach for the question.我对 mysql 非常陌生,并真诚地道歉,因为我正在努力为这个问题找到正确的方法。

I have a table which is containing the events schedule time:我有一个包含事件安排时间的表:

在此处输入图像描述

Event_id 1 will be running on every Monday in between 03-04-2022 to 03-12-2022.I need to find the total run count of the each Event_id in between a date range. Event_id 1 将在 2022 年 3 月 4 日至 2022 年 3 月 12 日之间的每个星期一运行。我需要找到一个日期范围内每个 Event_id 的总运行次数。

You need to find number of day between start and end date.您需要找到开始日期和结束日期之间的天数。 Eg how many Monday between start and end date for event_id=1 and so on.例如,在 event_id=1 的开始日期和结束日期之间有多少个星期一,依此类推。

In the question start_date and end_date for event_id=4 are not correct as start_date > end_date.在问题中,event_id=4 的 start_date 和 end_date 不正确,因为 start_date > end_date。 Also, there is a spelling mistake in day name for evnet_id=4.此外,evnet_id=4 的日期名称存在拼写错误。

The query used for getting the result, after fixing data issues is -修复数据问题后,用于获取结果的查询是 -

WITH RECURSIVE 
date_gen (gen_dt) AS
(
SELECT min(start_date) from event_tab
union all
SELECT date_add(gen_dt,interval 1 day) from date_gen where gen_dt < (select max(end_date) from event_tab)
)
SELECT 
e.event_id,
sum(case when dayname(d.gen_dt) =  e.schedule_day then 1 else 0 end ) day_nos_as_run_count
FROM date_gen d, event_tab e
where 
cast(d.gen_dt as date) between e.start_date and e.end_date
group by e.event_id

DB fiddle here . DB小提琴在这里

Recursive query example help from here .递归查询示例帮助来自这里

Sample output -样本输出 -

event_id event_id day_nos_as_run_count day_nos_as_run_count
1 1 35 35
2 2 23 23
3 3 2 2
4 4 0 0

Another variant of the query -查询的另一个变体 -

WITH RECURSIVE 
date_gen (gen_dt) AS
(
SELECT min(start_date) from event_tab
union all
SELECT date_add(gen_dt,interval 1 day) from date_gen where gen_dt < (select max(end_date) from event_tab)
)
SELECT 
e.event_id,
count(d.gen_dt)
FROM event_tab e left join date_gen d
on ( cast(d.gen_dt as date) between e.start_date and e.end_date
and e.schedule_day = dayname(d.gen_dt))
group by e.event_id
order by e.event_id

Start by storing dates in date format: 03-04-2022 should be stored as 2022-04-03 (assuming that your format is day-month-year).首先以日期格式存储日期: 03-04-2022应存储为2022-04-03 (假设您的格式为日-月-年)。 And store into a column declared to be DATE , not VARCHAR .并存储到声明为DATE而不是VARCHAR的列中。

Then you have the ability to use the DATEDIFF() function to get differences.然后您就可以使用DATEDIFF()函数来获取差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM