SQL从期间计数天数

发布于 2025-02-07 01:14:55 字数 1114 浏览 3 评论 0 原文

我的问题是,我想从5月起的日期列为日期,但是如下所示,某些事件从5月的第一天开始,而去年五月的某些事件开始。

有我的代码:

SELECT * FROM rooms p, bookings r WHERE p.id_room = r.id_room group by 
r.id_room having 
case
    WHEN (month(r.start_date) = 5 AND month(r.end_date) = 5) THEN 
    sum(datediff(r.end_date, r.start_date)) < 21
    WHEN (month(r.start_date) < 5 AND month(r.end_date) = 5) THEN 
    sum(datediff(r.end_date, '2022-05-01 12:00:00')) < 21
    WHEN (month(r.start_date) = 5 AND month(r.end_date) > 5) THEN 
    sum(datediff('2022-05-31 12:00:00', r.start_date)) < 21
END;

“

编辑1

“其他选项” 我只会在底部谈论示例。 例如 date_start- 6月3日 date_end- 6月15日

最大(date_start,'2022-05-1')6月3日返回 最少(date_end,'2022-05-31')5月31日回溯

(date_end,date_start)返回-3,但仍将其计为“ 5月”,而应跳过它

My problem is that I want to sum periods of date from only may, but as you can see below some of events starts before first day of may and some end after last may day.

There is my code:

SELECT * FROM rooms p, bookings r WHERE p.id_room = r.id_room group by 
r.id_room having 
case
    WHEN (month(r.start_date) = 5 AND month(r.end_date) = 5) THEN 
    sum(datediff(r.end_date, r.start_date)) < 21
    WHEN (month(r.start_date) < 5 AND month(r.end_date) = 5) THEN 
    sum(datediff(r.end_date, '2022-05-01 12:00:00')) < 21
    WHEN (month(r.start_date) = 5 AND month(r.end_date) > 5) THEN 
    sum(datediff('2022-05-31 12:00:00', r.start_date)) < 21
END;

3 examples

Edit 1

2 other options
I will only talk about example on bottom.
E.g.
date_Start - June 3
date_end - June 15

GREATEST(date_start, '2022-05-1') returns June 3
LEAST(date_end, '2022-05-31') retruns may 31

DATEDIFF(date_end, date_start) returns -3 and it is still counted as day from may while it should be skipped

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深巷少女 2025-02-14 01:14:55

通过使用函数 code> dist> 最大()

SELECT r.id_room  
FROM rooms r LEFT JOIN bookings b 
ON b.id_room = r.id_room 
AND b.end_date > '2022-05-01 12:00:00' AND b.start_date < '2022-05-31 12:00:00'
GROUP BY r.id_room 
HAVING SUM(COALESCE(DATEDIFF(
             LEAST(b.end_date, '2022-05-31 12:00:00'),
             GREATEST(b.start_date, '2022-05-01 12:00:00')
       ), 0)) < 21; 

另外,请使用适当的加入。

Simplify the HAVING clause by using the functions LEAST() and GREATEST():

SELECT r.id_room  
FROM rooms r LEFT JOIN bookings b 
ON b.id_room = r.id_room 
AND b.end_date > '2022-05-01 12:00:00' AND b.start_date < '2022-05-31 12:00:00'
GROUP BY r.id_room 
HAVING SUM(COALESCE(DATEDIFF(
             LEAST(b.end_date, '2022-05-31 12:00:00'),
             GREATEST(b.start_date, '2022-05-01 12:00:00')
       ), 0)) < 21; 

Also, use a proper join.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文