简体   繁体   English

计算和总和日期范围内的天数

[英]count and sum number of days in date ranges

I have the following table: 我有下表:

id | start_date  |  end_date  | client_id
1    2013-08-01    2013-08-09       1
2    2013-08-10    2013-08-10       1
3    2013-08-10    2013-08-17       1
4    2013-08-18    2013-08-18       1
5    2013-08-18    2013-08-18       1
6    2013-08-18    2013-08-31       1
7    2013-08-01    2013-08-09       2
8    2013-08-11    2013-08-11       2
9    2013-08-11    2013-08-17       2
10   2013-08-19    2013-08-20       2

what I'm trying to do is count the number of days that each client was present without repeating the days for each client, so from the previous data I'm looking to get: 我想要做的是计算每个客户端存在的天数而不重复每个客户的日期,所以从以前的数据我想得到:

client_id | total_days
    1           31
    2           18

So for client 1 I get 31 because he was "present" for 31 days, from 8/1/2013 - 8/31/2013 with no gaps, and for client 2 I get 18 because he was present for 18 days: 所以对于客户1我得到31因为他“存在”了31天,从2013年8月1日 - 2013年8月31日没有间隙,而对于客户2我得到18,因为他在场18天:

8/1 - 8/9 = 9 days 
8/11 - 8/17 = 7 days 
8/19 - 8/20 = 2 days

is there anyway to achieve this in MySQL, I've been trying for a while but have no idea on how to do it. 无论如何要在MySQL中实现这一点,我已经尝试了一段时间,但不知道如何做到这一点。

This is the fiddle 这是小提琴

If overlapping ranges exist, then I suggest building a driver table that is a list of dates, then JOIN to that table using BETWEEN : 如果存在重叠范围,那么我建议构建一个日期列表的驱动程序表,然后使用BETWEEN JOIN该表:

SELECT a.Client_ID, COUNT(DISTINCT b.Date)
FROM YourTable a
JOIN Dates b
  ON b.Date BETWEEN a.start_date  AND a.end_date
GROUP BY a.Client_ID

Demo: SQL Fiddle 演示: SQL小提琴

There are plenty of places to find calendar table logic, here's one. 有很多地方可以找到日历表逻辑, 这里是一个。

If ranges never overlap then you can use SUM(DATEDIFF()) . 如果范围从不重叠,则可以使用SUM(DATEDIFF())

If there are no overlapping ranges. 如果没有重叠范围。 You can use the following query: 您可以使用以下查询:

SELECT Client_id,
       Sum(DATEDIFF(End_date, Start_date)) AS `Present`
FROM TABLE
GROUP BY Client_id;

This will give you an overview of the number of days a client was present. 这将为您提供客户在场的天数概览。

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

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