tmieruch
tmieruch

Reputation: 191

Counting appointments for each day using MYSQL

I'm in trouble with a mysql statement counting appointments for one day within a given time period. I've got a calendar table including starting and finishing column (type = DateTime). The following statement should count all appointments for November including overall appointments:

SELECT 
    COUNT('APPOINTMENTS') AS Count, 
    DATE(c.StartingDate) AS Datum 
FROM t_calendar c
    WHERE 
        c.GUID = 'blalblabla' AND
        ((DATE(c.StartingDate) <= DATE('2012-11-01 00:00:00')) AND (DATE(c.EndingDate) >= DATE('2012-11-30 23:59:59'))) OR
        ((DATE(c.StartingDate) >= DATE('2012-11-01 00:00:00')) AND (DATE(c.EndingDate) <= DATE('2012-11-30 23:59:59')))
    GROUP BY DATE(c.StartingDate)
    HAVING Count > 1

But how to include appointments that starts before a StartingDate and ends on the StartingDate?

e.g.

My statement returns a count of 2 for 15th of November. But that's wrong because the first appointment is missing. How to include these appointments? What I am missing, UNION SELECT, JOIN, sub selection?


A possible solution?

SELECT 
    c1.GUID, COUNT('APPOINTMENTS') + COUNT(DISTINCT c2.ANYFIELD) AS Count, 
    DATE(c1.StartingDate) AS Datum,
    COUNT(DISTINCT c2.ANYFIELD)
FROM 
    t_calendar c1
LEFT JOIN
    t_calendar c2
        ON
            c2.ResourceGUID = c1.ResourceGUID AND
            (DATE(c2.EndingDate) = DATE(c1.StartingDate)) AND 
            (DATE(c2.StartingDate) < DATE(c1.StartingDate))
WHERE 
    ((DATE(c1.StartingDate) <= DATE('2012-11-01 00:00:00')) AND (DATE(c1.EndingDate) >= DATE('2012-11-30 23:59:59'))) OR
    ((DATE(c1.StartingDate) >= DATE('2012-11-01 00:00:00')) AND (DATE(c1.EndingDate) <= DATE('2012-11-30 23:59:59')))    
GROUP BY 
    c1.ResourceGUID,
    DATE(c1.StartingDate)

Upvotes: 2

Views: 3203

Answers (1)

Robert Koritnik
Robert Koritnik

Reputation: 105029

First: Consolidate range checking

First of all your two range where conditions can be replaced by a single one. And it also seems that you're only counting appointments that either completely overlap target date range or are completely contained within. Partially overlapping ones aren't included. Hence your question about appointments that end right on the range starting date.

To make where clause easily understandable I'll simplify it by using:

  • two variables to define target range:
    • rangeStart (in your case 1st Nov 2012)
    • rangeEnd (I'll rather assume to 1st Dec 2012 00:00:00.00000)
  • won't be converting datetime to dates only (using date function) the way that you did, but you can easily do that.

With these in mind your where clause can be greatly simplified and covers all appointments for given range:

...
where (c.StartingDate < rangeEnd) and (c.EndingDate >= rangeStart)
...

This will search for all appointments that fall in target range and will cover all these appointment cases:

                           start          end
target range               |==============|

partial front       |---------|
partial back                            |---------|
total overlap          |---------------------|
total containment               |-----|

Partial front/back may also barely touch your target range (what you've been after).

Second: Resolving the problem

Why you're missing the first record? Simply because of your having clause that only collects those groups that have more than 1 appointment starting on a given day: 15th Nov has two, but 14th has only one and is therefore excluded because Count = 1 and is not > 1.

To answer your second question what am I missing is: you're not missing anything, actually you have too much in your statement and needs to simplified.

Try this statement instead that should return exactly what you're after:

select count(c.GUID) as Count,
       date(c.StartingDate) as Datum
from t_calendar c
where (c.GUID = 'blabla') and
      (c.StartingDate < str_to_date('2012-12-01', '%Y-%m-%d') and
      (c.EndingDate >= str_to_date('2012-11-01', '%Y-%m-%d'))
group by date(c.StartingDate)

I used str_to_date function to make string to date conversion more safe.

I'm not really sure why you included having in your statement, because it's not really needed. Unless your actual statement is more complex and you only included part that's most relevant. In that case you'll likely have to change it to:

having Count > 0

Getting appointment count per day in any given date range

There are likely other ways as well but the most common way would be using a numbers or ?calendar* table that gives you the ability to break a range into individual points - days. They you have to join your appointments to this numbers table and provide results.

I've created a SQLFiddle that does the trick. Here's what it does...

Suppose you have numbers table Num with numbers from 0 to x. And appointments table Cal with your records. Following script created these two tables and populates some data. Numbers are only up to 100 which is enough for 3 months worth of data.

-- appointments
create table Cal (
  Id int not null auto_increment primary key,
  StartDate datetime not null,
  EndDate datetime not null
);

-- create appointments
insert Cal (StartDate, EndDate)
values
  ('2012-10-15 08:00:00', '2012-10-20 16:00:00'),
  ('2012-10-25 08:00:00', '2012-11-01 03:00:00'),
  ('2012-11-01 12:00:00', '2012-11-01 15:00:00'),
  ('2012-11-15 10:00:00', '2012-11-16 10:00:00'),
  ('2012-11-20 08:00:00', '2012-11-30 08:00:00'),
  ('2012-11-30 22:00:00', '2012-12-05 00:00:00'),
  ('2012-12-01 05:00:00', '2012-12-10 12:00:00');

-- numbers table
create table Nums (
  Id int not null primary key
);

-- add 100 numbers
insert into Nums
select a.a + (10 * b.a)
from (select 0 as a union all
      select 1 union all
      select 2 union all
      select 3 union all
      select 4 union all
      select 5 union all
      select 6 union all
      select 7 union all
      select 8 union all
      select 9) as a,
     (select 0 as a union all
      select 1 union all
      select 2 union all
      select 3 union all
      select 4 union all
      select 5 union all
      select 6 union all
      select 7 union all
      select 8 union all
      select 9) as b

Now what you have to do now is

  1. Select a range of days which you do by selecting numbers from Num table and convert them to dates.
  2. Then join your appointments to those dates so that those appointments that fall on particular day are joined to that particular day
  3. Then just group all these appointments per each day and get results

Here's the code that does this:

-- just in case so comparisons don't trip over
set names 'latin1' collate latin1_general_ci;

-- start and end target date range
set @s := str_to_date('2012-11-01', '%Y-%m-%d');
set @e := str_to_date('2012-12-01', '%Y-%m-%d');

-- get appointment count per day within target range of days
select adddate(@s, n.Id) as Day, count(c.Id) as Appointments
from Nums n
  left join Cal c
  on ((date(c.StartDate) <= adddate(@s, n.Id)) and (date(c.EndDate) >= adddate(@s, n.Id)))
where adddate(@s, n.Id) < @e
group by Day;

And this is the result of this rather simple select statement:

|        DAY | APPOINTMENTS |
-----------------------------
| 2012-11-01 |            2 |
| 2012-11-02 |            0 |
| 2012-11-03 |            0 |
| 2012-11-04 |            0 |
| 2012-11-05 |            0 |
| 2012-11-06 |            0 |
| 2012-11-07 |            0 |
| 2012-11-08 |            0 |
| 2012-11-09 |            0 |
| 2012-11-10 |            0 |
| 2012-11-11 |            0 |
| 2012-11-12 |            0 |
| 2012-11-13 |            0 |
| 2012-11-14 |            0 |
| 2012-11-15 |            1 |
| 2012-11-16 |            1 |
| 2012-11-17 |            0 |
| 2012-11-18 |            0 |
| 2012-11-19 |            0 |
| 2012-11-20 |            1 |
| 2012-11-21 |            1 |
| 2012-11-22 |            1 |
| 2012-11-23 |            1 |
| 2012-11-24 |            1 |
| 2012-11-25 |            1 |
| 2012-11-26 |            1 |
| 2012-11-27 |            1 |
| 2012-11-28 |            1 |
| 2012-11-29 |            1 |
| 2012-11-30 |            2 |

Upvotes: 4

Related Questions