T-SQL:前5个查询中的月份

时间:2013-06-25 17:11:38

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

基本查询是:

SELECT Top 5 
[Year], [Month], Title, Units, [Rank]
from aTable
WHERE [Year] = @Year and [Month] = @Month
order by [Rank] desc

我想补充一点,就是[前五名中的月份]列,它会显示连续几个月,前五名中的每一行都排名为5或更低。

1 个答案:

答案 0 :(得分:1)

;with myTable as (
    select
        dateadd(yy,[Year]-1900,0) + dateadd(mm,[Month]-1,0) YearMonth,
        Title,
        Units,
        Rank
    from
        aTable
),
results as (

    select
        YearMonth,
        Title, 
        Units, 
        [Rank]
    from
        myTable
    where
        YearMonth = dateadd(m,datediff(m,0,getdate()),0) and
        Rank <= 5
    union all
    select
        b.YearMonth,
        b.Title, 
        b.Units, 
        0 Rank
    from
        myTable b
        join results a on
            b.Title = a.Title and 
            b.YearMonth = dateadd(m,-1,a.YearMonth) and 
            b.Rank <=5
)
select 
    max(YearMonth),
    Title,
    sum(Units) Units,
    max(Rank) Rank,
    count(*) MonthsInTop5
from
    results
group by
    Title
order by
    Rank Desc