SQL returns dates that fall in period and range

I was silent for a bit about this ... My goal is to return all dates that are between the start and end dates, and have a certain period as a factor from the start date. (hard to explain)

For instance...

Start date: November 20, 1987; End date: January 01, 1988; Period: 10 days;

I want these dates: November 20, 1987; November 30, 1987; December 10, 1987; December 20, 1987; December 30, 1987;

I already have a date table with all dates from 1900 to 2099. The period may be days, months or years. Any ideas? Let me know if you need more information.

MySQL

+3
source share
2 answers

DATEDIFF modulo:

SELECT * FROM dates
WHERE `date` BETWEEN '1987-10-20' AND '1988-1-1'
AND DATEDIFF(`date`, '1987-10-20') % 10 = 0

10 , :

SELECT * FROM dates
WHERE `date` BETWEEN '1980-10-20' AND '2000-10-20'
AND MONTH(date) = 10 AND DAY(date) = 20 AND (YEAR(date) - 1980) % 10 = 0

, , , . , 30 ? , " ".

+7

MS SQL Server 2005 , :

WITH Days AS
(
    SELECT CONVERT(DATETIME, '11/20/87') AS Date
    UNION ALL
    SELECT DATEADD(DAY, 10, Days.Date) AS Date
    FROM Days
    WHERE Days.Date < '1/1/88'
)
SELECT Days.Date
FROM Days
WHERE Days.Date < '1/1/88'
+1

Source: https://habr.com/ru/post/1737430/


All Articles