Answer the question
In order to leave comments, you need to log in
How to correctly compose a query to select days from a range of dates?
The table stores cases that have a start date and an end date (field type DATETIME).
id | date_from | date-_to
---------------------------------------------------- -------------
1 | 2015-11-02 00:00:00 | 2015-11-02 23:59:59
2 | 2015-11-02 09:00:00 | 2015-11-02 18:00:00
3 | 2015-11-02 00:00:00 | 2015-12-01 23:59:59
4 | 2016-01-01 00:00:00 | 2016-01-01 23:59:59
I need to display the days on which these tasks are relevant
SELECT *, DATE_FORMAT(date_from, '%m-%d-%Y') AS date_from_date FROM `task` GROUP BY date_from_date
Answer the question
In order to leave comments, you need to log in
SELECT DATE_ADD(date_from, INTERVAL rn DAY) AS `date`
FROM task
INNER JOIN (
SELECT @rn := @rn + 1 AS rn
FROM (
SELECT *
FROM (
SELECT 1 AS n1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
) AS t1 CROSS JOIN (
SELECT 1 AS n2 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
) AS t2
) AS t CROSS JOIN (SELECT @rn := -1) AS var
) AS tally ON DATEDIFF(date_to, date_from) >= rn
ORDER BY `date`
SELECT
GROUP_CONCAT (id),
DATE_FORMAT(date_from, '%m-%d-%Y') AS date_from_date,
DATE_FORMAT(date_to, '%m-%d-%Y') AS date_to_date
FROM `task`
GROUP BY DATE_FORMAT(date_from , '%m-%d-%Y') ,
DATE_FORMAT(date_to, '%m-%d-%Y')
What do you want to receive? string with dates for each task? then:
DELIMITER $$
--
-- Create function "calc_date_range"
--
CREATE FUNCTION calc_date_range(date_start DATE, date_end DATE)
RETURNS text CHARSET latin1
SQL SECURITY INVOKER
BEGIN
DECLARE res_text text;
DECLARE tmp_date date;
IF(date_end < date_start) THEN
RETURN '';
END IF;
SET tmp_date := date_start;
SET res_text :='';
WHILE(tmp_date<=date_end) DO
SET res_text := CONCAT(res_text,',',DATE_FORMAT(tmp_date, '%m-%d-%Y'));
SET tmp_date := DATE_ADD(tmp_date, INTERVAL 1 DAY);
END WHILE;
RETURN SUBSTRING(res_text,2);
END
SELECT c.cdate FROM tasks t
INNER JOIN calendar c ON c.cdate >= DATE(t.date_from) AND c.cdate<=DATE(t.date_to)
WHERE
t.USER_ID = 17
AND t.status = 4
AND NOT c .weekend = 1
GROUP BY c.cdate;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question