我有像这样的年表。每年都有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 但都是徒劳的。
答案 0 :(得分:5)
使用 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)
答案 1 :(得分: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