基本查询是:
SELECT Top 5
[Year], [Month], Title, Units, [Rank]
from aTable
WHERE [Year] = @Year and [Month] = @Month
order by [Rank] desc
我想补充的是[前 5 名中的月份] 列,它将显示前 5 名中的每一行的连续月份数为 5 或更少。
基本查询是:
SELECT Top 5
[Year], [Month], Title, Units, [Rank]
from aTable
WHERE [Year] = @Year and [Month] = @Month
order by [Rank] desc
我想补充的是[前 5 名中的月份] 列,它将显示前 5 名中的每一行的连续月份数为 5 或更少。
;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