Skip to content
Advertisement

How to update Query to calc SUM or COUNT using two dates and BETWEEN?

My current query is as such:

It produces the following results that we use in Google Charts to show the number of reservations per month. The issue is we are only getting the number of times a reservation is created, not the number of days between the start date (date) and the end date (dateLast).

I’ve been trying the following update but getting an error related to the BETWEEN operator:

MySQL said: Documentation

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘BETWEEN date AND dateLast) AS D, CONCAT(LEFT(MONTHNAME(DATE),’ at line 2

The goal is to get a SUM for all days reserved between AND including date to dateLast Note: dateLast is not counted as it is the Checkout date. Maybe this is too complex for a SQL query and should be handled in PHP as a series of sub-routines?

Advertisement

Answer

If you don’t need to split the number of days of one reservation over multiple months, then you can just use SUM(DATEDIFF(dateLast, date))

db-fiddle

If you want to split them, then I hope your version (MySQL 8+ or MariaDB 10.2+) supports recursive queries. In that case you can expand the date range to one row per day in the range and count them:

db-fiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement