Search code examples
mysqlsqlconstraintsdate-range

SQL: Count/ sum columns within a specific date range


I have a table that roughly looks like this. There are thousands of rows.

booking_date   checkin_date    ...some other columns  ....    booking_value
22-mar-2016      29-mar-2016   ...........................         $150
01-apr-2016      17-may-2016   ...........................         $500
09-apr-2016      09-apr-2016   ...........................         $222
17-apr-2016      23-apr-2016  ...........................          $75
19-apr-2016      31-july-2016 ...........................          $690
03-May-2016      07-May-2016  .............................        $301
.
.
.
.

I am trying to calculate number of bookings per day and the value of bookings per day in April 2016. The second part is to calculate for how many bookings the booking_date and checking_date were the same.

I am very new to SQL. I can formulate the logic in paper, but can't seem to figure out how to proceed with the code.


Solution

  • I recommend the following query:

    SELECT CAST(booking_date AS DATE), COUNT(*) as Number_of_Booking,
           SUM(CAST(booking_date AS DATE) = CAST(checkin_date AS DATE)) as count_with_same_date,
           SUM(booking_value) as booking_value
    FROM t
    WHERE booking_date >= '2016-04-01' AND
          booking_date < '2016-05-01'
    GROUP BY CAST(booking_date AS DATE);
    

    In particular, note the filtering on the dates. The direct comparisons allow MySQL to use an index.

    The calculation of the number on the same date uses a nice feature of MySQL where boolean values are treated as numbers in a numeric context.