按顺序使用where子句中列的值

时间:2016-10-06 01:32:51

标签: sql-server

我有一个体育数据库(板球,有点像我美国朋友的棒球)我在一个赛季中获得最多门票(棒球比赛)的查询如下:

select top(5)
S.Season,
TT.Team,
P.LastCommaSpaceFirst,
SUM(PIS.Wickets) AS 'Wickets'
from PlayerInningsSummary PIS
join Personel P on P.PersonID = PIS.PlayerID
join InningsSummary INS on PIS.InningsSummaryID = INS.InningsSummaryID
join Matches M on INS.MatchID = M.MatchID
join Seasons S on M.SeasonID = S.SeasonID
join Teams TT on M.TeamID = TT.TeamID
where TT.Team = '1st XI' --and S.Season = '1973/1974'
group by S.Season, TT.Team, P.LastCommaSpaceFirst
order by Wickets desc

所以这个查询得到了一个季节中最多的人(1973/1974,在这种情况下)获得最多的人。

查询效果很好,但我想迭代我所有的季节(例如:1974 / 1975,7975 / 1975等)。

我该怎么做?我认为ROW_OVER和PARTITION BY是可行的方法,但我无法弄清楚如何让它发挥作用。

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

像这样的东西

Select * from
(
select Row_number() over(Partition by S.Season Order by SUM(PIS.Wickets) desc) as RN
S.Season,
TT.Team,
P.LastCommaSpaceFirst,
SUM(PIS.Wickets) AS 'Wickets'
from PlayerInningsSummary PIS
join Personel P on P.PersonID = PIS.PlayerID
join InningsSummary INS on PIS.InningsSummaryID = INS.InningsSummaryID
join Matches M on INS.MatchID = M.MatchID
join Seasons S on M.SeasonID = S.SeasonID
join Teams TT on M.TeamID = TT.TeamID
where TT.Team = '1st XI' --and S.Season = '1973/1974'
group by S.Season, TT.Team, P.LastCommaSpaceFirst
) A
Where RN <= 5