建立年和季度组合表

时间:2018-11-04 23:33:10

标签: sql sql-server

说我有一个一年和一个季度,我想建立一个表格,列出以给定的年份和季度结束的特定数量的年份和季度组合。

例如

**Input:** 
Year = 2018 
Quarter = 3 
NumRows = 4

**Output:** 
Year.....|Quarter
2018.....|3
2018.....|2
2018.....|1
2017.....|4

3 个答案:

答案 0 :(得分:3)

您可以使用递归生成。

首先,您需要根据年份和季度构建一个DATETIME对象。

DECLARE @Quarter INT = 3;
DECLARE @Year INT = 2018;
DECLARE @NumRows INT = 4;

DECLARE @initial_date DATETIME = DATEADD(quarter, @Quarter-1, DATEADD(year, @Year-1900, 0));

然后,您可以像这样递归生成年份和季度组合。

;WITH quarters AS (
    SELECT @initial_date AS [qdate]
    UNION ALL
    SELECT DATEADD(quarter, -1, [qdate])  AS [qdate]
    FROM quarters
    WHERE [qdate] > DATEADD(quarter, -1*(@NumRows-1), @initial_date)
)
SELECT DATEPART(year, qdate) as year, DATEPART(quarter, qdate) as quarter FROM quarters

答案 1 :(得分:1)

您可以尝试使用cte递归进行一些计算

DECLARE @Year INT= 2018 
DECLARE @Quarter INT = 3 
DECLARE @NumRows INT= 10

;WITH CTE AS (
    SELECT (@Year - @NumRows/4) yr,
            4 - (@NumRows % 4) Quarter,
        @NumRows NumRows
    UNION ALL
    SELECT  yr + Quarter / 4, 
         CASE WHEN (Quarter + 1) % 4 = 0 THEN 4 
             ELSE (Quarter + 1) % 4 
         END,
        NumRows- 1
    FROM CTE
    WHERE NumRows > 1
)
select yr,Quarter 
from cte

sqlfiddle

答案 2 :(得分:1)

这使用递归cte

对于

declare @year       int = 2018,
        @quarter    int = 3,
        @numrows    int = 6


; with rcte as
(
    select  n   = 1,
        yr  = @year,
        qtr = @quarter

    union all

    select  n   = n + 1,
            yr  = yr - (((qtr - 1 + 4 - 1) % 4 + 1) / 4),
            qtr = (qtr - 1 + 4 - 1) % 4 + 1
    from    rcte
    where   n   < @numrows
)
select  *
from    rcte
order by n

/* result:
n   yr      qtr
1   2018    3
2   2018    2
3   2018    1
4   2017    4
5   2017    3
6   2017    2
*/