如何使用SQL在接下来的5年中每月选择同一天?
例如:
我试过了:
select dateadd(day,-day(dateadd(month,1,current_timestamp)) , dateadd(month,1,current_timestamp) )
答案 0 :(得分:7)
像
这样的东西DECLARE @StartDate DATETIME = '05 Jan 2013',
@YearsAdded INT = 5
;WITH Dates AS (
SELECT @StartDate [Date]
UNION ALL
SELECT DATEADD(MONTH,1,[Date])
FROM Dates
WHERE DATEADD(MONTH,1,[Date]) <= DATEADD(YEAR,@YearsAdded,@StartDate)
)
SELECT *
FROM Dates
OPTION (MAXRECURSION 0)
答案 1 :(得分:1)
这非常适合计数表
月刊
--========================================================================================================================
/* tally */
--========================================================================================================================
;WITH parms AS (SELECT
YearSpan = 5
,DayOfTheMonth = 5
)
,E1(N) AS (
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 UNION ALL SELECT 1
)
, Tally(N) AS (
SELECT 0 UNION
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM E1 a, E1 b
)
--========================================================================================================================
/* projection */
--========================================================================================================================
SELECT
ResultDate = DATEADD(mm, DATEDIFF(mm, 0, DATEADD(mm, t.N, GETDATE())), (p.DayOfTheMonth - 1))
FROM parms p
CROSS JOIN Tally t
WHERE DATEADD(mm, t.N, GETDATE()) < DATEADD(yy, p.YearSpan, GETDATE())
QUARTERLY(使用与MONTHLY相同的“tally”代码块,所以我省略了它的代码)
--========================================================================================================================
/* tally */
--========================================================================================================================
-- [code omitted]
--========================================================================================================================
/* projection */
--========================================================================================================================
SELECT
ResultDate = DATEADD(qq, DATEDIFF(qq, 0, DATEADD(qq, t.N, GETDATE())), (p.DayOfTheMonth - 1))
FROM parms p
CROSS JOIN Tally t
WHERE DATEADD(qq, t.N, GETDATE()) < DATEADD(yy, p.YearSpan, GETDATE())