如何获得给财政年度的月份和年份价值

时间:2014-12-08 13:58:20

标签: sql database sql-server-2008

如何获得给定财政年度的月和年值

如果我的输入是2013年。 我的预期结果是

Month  Year 
4       2013
5       2013
6       2013
7       2013
8       2013
9       2013
10      2013
11      2013
12      2013
1       2014
2       2014
3       2014

1 个答案:

答案 0 :(得分:0)

使用Recursive CTE获得预期结果。

DECLARE @nYearInput AS CHAR(4)
DECLARE @start DATETIME, @end DATETIME

SET @nYearInput = '2013'  -- Change your input here

SET @start = CAST(@nYearInput AS VARCHAR) + '0401'
SET @end= CAST(@nYearInput + 1 AS VARCHAR) + '0301'

;WITH cte AS 
(
    SELECT dt = DATEADD(DAY, -(DAY(@start) - 1), @start)

    UNION ALL

    SELECT DATEADD(MONTH, 1, dt)
    FROM cte
    WHERE dt < DATEADD(DAY, -(DAY(@end) - 1), @end)
)
SELECT YEAR(dt) AS Year, month(dt) AS month
FROM cte