I have a table of events each with a given start and end date.
CREATE TABLE dataset (
id int(11) unsigned NOT NULL AUTO_INCREMENT,
event varchar(64) NOT NULL DEFAULT '',
valid_from date DEFAULT NULL,
valid_to date DEFAULT NULL,
PRIMARY KEY (id)
);
INSERT INTO dataset (event, valid_from, valid_to) VALUES
('Test1', '2014-12-01', '2014-12-01'),
('Test2', '2014-12-02', '2014-12-02'),
('Test3', '2014-12-03', '2014-12-03'),
('Test4', '2014-12-04', '2014-12-04'),
('Test5', '2014-12-05', '2014-12-05'),
('Test6', '2014-12-01', '2014-12-01'),
('Test7', '2014-12-01', '2014-12-07');
I need help with a query to get the number of max concurrent events in a given range of dates. If start and end date are the same its working as expected with this query:
SET @d1 = '2014-12-01';
SET @d2 = '2014-12-01';
SELECT COUNT(*) as valid_events FROM dataset WHERE @d2 >= valid_from AND valid_to >= @d1;
This will return 3 which is true for the 1st of December it matches Test1, Test6 and Test7. But if I extend the range it stops working for me:
SET @d1 = '2014-12-01';
SET @d2 = '2014-12-07';
SELECT COUNT(*) as valid_events FROM dataset WHERE @d2 >= valid_from AND valid_to >= @d1;
This returns 7 because all the events overlap with the start and end date but I want them only to be counted if they overlap with each other as well.
Test1 Test2 Test3 Test4 Test5 Test6 Test7 Result
2014-12-01 X X X 3
2014-12-02 X X 2
2014-12-03 X X 2
2014-12-04 X X 2
2014-12-05 X X 2
2014-12-06 X 1
2014-12-07 X 1
So if I request the max amount of concurrent events between 1st and 7th December I want to have the result of 3 and not 7.