SQL排名日期以获得年度订单

时间:2013-08-09 18:14:28

标签: sql sql-server-2008 tsql ranking rank

我有一个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月(当月)。我无法弄清楚如何从当月开始。我确信它非常简单,我只是想念它。谢谢!

1 个答案:

答案 0 :(得分: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 fiddle示例