1

我有一个 YYYYMM 格式的日期列表,我正在尝试以年复一年的格式对它们进行排名,如下所示:

MonthDisplay  YearMonth  Rank  MonthNumber YearNumber
Aug-2013      201308     1     8           2013
Aug-2012      201208     2     8           2012
Jul-2013      201307     3     7           2013
Jul-2012      201207     4     7           2012

我已经能够通过使用以下排名来接近它并获得以下结果:

RANK() OVER(PARTITION BY 1 ORDER BY MonthNumber DESC, YearNumber DESC)

Month     YearMonth  Rank  
Dec-2012  201212     1     
Dec-2011  201112     2     
Nov-2012  201211     114   
Nov-2011  201111     115   
Oct-2012  201210     227   
Oct-2011  201110     228   

但是,这从 2012 年 12 月开始,而不是从 2013 年 8 月(当月)开始。我不知道如何让它从本月开始。我确信它超级简单,我只是想念它。谢谢!

4

1 回答 1

3
select
   T.YearMonth,
   rank() over (order by R.rnk asc, D.YearNumber desc) as [Rank],
   D.MonthNumber, D.YearNumber
from Table1 as T
    outer apply (
        select 
            month(getdate()) as CurMonthNumber,
            cast(right(T.YearMonth, 2) as int) as MonthNumber,
            cast(left(T.YearMonth, 4) as int) as YearNumber
    ) as D
    outer apply (
        select
            case
                when D.MonthNumber <= D.CurMonthNumber then
                    D.CurMonthNumber - D.MonthNumber
                else
                    12 + D.CurMonthNumber - D.MonthNumber
            end as rnk      
    ) as R

sql小提琴示例

于 2013-08-09T19:59:35.003 回答