Last active
April 13, 2020 10:22
-
-
Save clxy/52fdcfe2ab9406dfa49a27bbe4f478b0 to your computer and use it in GitHub Desktop.
MS SQL Server - create list of month by with clause. @see https://stackoverflow.com/a/9255298
This file contains hidden or 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
--- | |
-- Personally, I liked this one! | |
--- | |
declare @ym_to date = cast('20190401' as date); | |
declare @ym_from date = cast('20181201' as date); | |
with months(dt) as ( | |
select @ym_to dt | |
union all | |
select dateadd(month, -1, dt) from months | |
) | |
select | |
top (datediff(month, @ym_from, @ym_to) + 1) | |
format(months.dt, 'yyyyMM') ym | |
from months | |
option (maxrecursion 13); |
This file contains hidden or 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 @ym_to date = cast('20190401' as date); | |
declare @ym_from date = cast('20181201' as date); | |
with | |
months as ( | |
--==== creates a "tally table" structure for months to add to start date | |
-- calulated by the difference in months between the start and end date. | |
-- then adds those numbers to the start of the month of the start date. | |
select | |
top (datediff(month, @ym_from, @ym_to) + 1) | |
dt = dateadd(month, datediff(month, 0, @ym_from) + (row_number() over (order by (select null)) -1), 0) | |
from sys.all_columns ac1 | |
cross join sys.all_columns ac2 | |
) | |
--===== slice each "whole month" date into the desired display values. | |
select format(months.dt, 'yyyyMM') ym | |
from months; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment