2

我有一张这样的年表。每年都有12(固定)

declare @t table (FiscalYear int,[Month] varchar(25))
insert into @t values
(2011,'Jan'),(2011,'Feb'),(2011,'Mar'),(2011,'Apr'),
(2011,'May'),(2011,'Jun'),(2011,'Jul'),(2011,'Aug'),
(2011,'Sep'),(2011,'Oct'),(2011,'Nov'),(2011,'Dec'),
(2012,'Jan'),(2012,'Feb'),(2012,'Mar'),(2012,'Apr'),
(2012,'May'),(2012,'Jun'),(2012,'Jul'),(2012,'Aug'),
(2012,'Sep'),(2012,'Oct'),(2012,'Nov'),(2012,'Dec'),
(2013,'Jan'),(2013,'Feb'),(2013,'Mar'),(2013,'Apr'),
(2013,'May'),(2013,'Jun'),(2013,'Jul'),(2013,'Aug'),
(2013,'Sep'),(2013,'Oct'),(2013,'Nov'),(2013,'Dec')

我想输出为

FYear   Month   Qt  Qtp
2011    Jan     1   1
2011    Feb     1   2
2011    Mar     1   3
2011    Apr     2   1
2011    May     2   2
2011    Jun     2   3
2011    Jul     3   1
2011    Aug     3   2
2011    Sep     3   3
2011    Oct     4   1
2011    Nov     4   2
2011    Dec     4   3
2012    Jan     1   1
2012    Feb     1   2
2012    Mar     1   3
2012    Apr     2   1
2012    May     2   2
2012    Jun     2   3
2012    Jul     3   1
2012    Aug     3   2
2012    Sep     3   3
2012    Oct     4   1
2012    Nov     4   2
2012    Dec     4   3
2013    Jan     1   1
2013    Feb     1   2
2013    Mar     1   3
2013    Apr     2   1
2013    May     2   2
2013    Jun     2   3
2013    Jul     3   1
2013    Aug     3   2
2013    Sep     3   3
2013    Oct     4   1
2013    Nov     4   2
2013    Dec     4   3

我怎么能做到这一点SQLServer2008R2。我尝试过使用DenseRank、RowNuber、Partitioned,但都是徒劳的。

4

2 回答 2

5

Tru 使用Ntile

--select * from @t      
SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY FYear, Qt ORDER BY FYear ) Qtp   
from
(SELECT FYear,[Month],
NTILE(4) OVER ( PARTITION BY FYear ORDER BY FYear ) AS Qt
FROM @t) PERIOD
ORDER BY FYear ,Qt ,ROW_NUMBER() OVER ( PARTITION BY FYear, Qt ORDER BY FYear)
于 2013-04-24T13:43:47.280 回答
1

我建议使用从 2013 年 12 月到您喜欢的年份的日期值动态填充表格(您可以更改 @COUNT_Y 变量以添加更多年份)。

SQL 有一些有趣的日期时间函数,比如 DATEPART,它可以告诉你一个月的哪个季度等。

** 答案因问题改变而改变 **

    DECLARE @DATES TABLE
    (
        xDATE DATETIME
    )

    DECLARE @STARTDATE DATETIME = '12-31-2013'

    DECLARE @COUNT_X INT = 0
    DECLARE @COUNT_X_MAX INT = 11

    DECLARE @COUNT_Y INT = 0
    DECLARE @COUNT_Y_MAX INT = 2

    WHILE (@COUNT_Y <= @COUNT_Y_MAX)
    BEGIN

        SET @COUNT_X = 0

        WHILE (@COUNT_X <= @COUNT_X_MAX)
        BEGIN

            INSERT INTO @DATES
            SELECT DATEADD(MONTH, -@COUNT_X, DATEADD(YEAR,-@COUNT_Y, @STARTDATE))

            SET @COUNT_X = @COUNT_X + 1
        END

        SET @COUNT_Y = @COUNT_Y + 1
    END

    SELECT * FROM
    (SELECT
    DATEPART(YEAR, D.xDATE) AS [YEAR],
    DATEPART(MONTH, D.xDATE) AS [MONTH],
    DATENAME(MONTH, D.xDATE) AS [MONTH_NAME],
    DATEPART(QUARTER, D.xDATE) AS [QUARTER],
    DATEPART(MONTH, D.xDATE) - (3 * (DATEPART(QUARTER, D.xDATE) - 1)) AS [QTP]
    FROM @DATES D) t
    ORDER BY T.YEAR, T.MONTH
于 2013-04-24T13:43:19.877 回答