MYSQL 5.7 question (NOT spreadsheet question) I've been stumped on this for a week (spreadsheet below is just for illustration purposes)
Orders are entered per customer within date range
-
order_number, quantity, start_date, end_date
-
01, 100, 2021-01-14, 2021-01-16
-
02, 125, 2021-01-14, 2021-01-16
-
03, 200, 2021-01-17, 2021-01-23
-
04, 050, 2021-01-14, 2021-01-19
-
…
-
10, 150, 2021-01-21, 2021-01-16
I need to find the MAX within an entered date range as illustrated in the table below.
ie. I enter variable start_date_search (2021-01-14) and end_date_search (2021-01-23), and I come up with the MAX on any given day within the range (675 in this example below.)
I don't need to output the totals for each day, but that would be cool too.
Schema (MySQL v5.7)
CREATE TABLE timetable (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
quantity INT(6) NOT NULL,
start_dt DATETIME,
end_dt DATETIME
);
INSERT INTO timetable (quantity, start_dt, end_dt)
VALUES (100, '2021-01-14 10:00:00', '2021-01-16 10:00:00'),
(125, '2021-01-14 10:00:00', '2021-01-16 10:00:00'),
(200, '2021-01-17 10:00:00', '2021-01-23 10:00:00'),
(50, '2021-01-14 10:00:00', '2021-01-19 10:00:00'),
(100, '2021-01-21 10:00:00', '2021-01-23 10:00:00'),
(75, '2021-01-16 10:00:00', '2021-01-21 10:00:00'),
(100, '2021-01-16 10:00:00', '2021-01-19 10:00:00'),
(200, '2021-01-16 10:00:00', '2021-01-19 10:00:00'),
(50, '2021-01-18 10:00:00', '2021-01-19 10:00:00'),
(150, '2021-01-21 10:00:00', '2021-01-23 10:00:00')
Best Answer
You will need a calendar table to distribute the quantity to each date in the interval:
Now you can use a join for that:
A calendar table is very useful for many tasks so I suggest you create one and populate it. Many DBMS including newer versions of MySQL support recursive CTE:s which can be used instead.
Getting the totals for each dt:
Fiddle