Last active
May 21, 2020 23:08
-
-
Save mizrael/c44e575008f5ab98994f to your computer and use it in GitHub Desktop.
SQL - select first/last days of months in a interval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @StartDate DATETIME, @EndDate DATETIME; -- don't forget to set them! | |
-- for example: | |
-- SELECT @StartDate = min(OrderDate), @EndDate = max(OrderDate) from Orders; | |
IF OBJECT_ID('tempdb..#dates') IS NOT NULL | |
DROP TABLE #dates | |
;WITH months ( [date] ) | |
AS | |
( | |
SELECT @StartDate | |
UNION ALL | |
SELECT DATEADD(MONTH, 1, [date]) | |
FROM months | |
WHERE DATEADD(MONTH, 1, [date]) <= @EndDate | |
) | |
SELECT DATENAME(MONTH,[date]) + ' ' + DATENAME(YEAR, [date]) as [date_text] | |
, DATEADD(MONTH, DATEDIFF(MONTH, 0, [date]), 0) as [start_date] | |
, DATEADD(SECOND, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, [date]) + 1, 0) ) as [end_date] | |
INTO #dates | |
FROM months; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment