我正在使用一个表格,其中包含有关历史足球比赛的一些统计信息,该表格看起来(简化)如下:
game_id game_date home_team away_team home_goal away_goal
1 01/01/2001 A B 0 1
2 01/01/2001 C D 2 0
3 01/02/2001 A C 1 0
4 01/02/2001 B D 0 1
5 01/03/2001 D A 3 4
6 01/03/2001 C B 1 2
现在,我想选择每支球队最近参加的10场比赛(按日期)(无论是在家还是在外比赛都没有区别)。结果(最近2场比赛)应如下所示:
game_id game_date home_team away_team home_goal away_goal
5 01/03/2001 D A 3 4
6 01/03/2001 C B 1 2
3 01/02/2001 A C 1 0
4 01/02/2001 B D 0 1
这是我对一个团队(A队)的查询:
SELECT * FROM game_table
WHERE home_team = A
OR away_team = A
ORDER BY game_date DESC
LIMIT 10
是否可以泛化此查询以获取表中所有团队的结果?
答案 0 :(得分:2)
让我假设您有一个团队表。在这种情况下,我认为apply
是最简单的方法:
SELECT g.*
FROM teams t CROSS APPLY
(SELECT TOP (10) g.*
FROM game_table g
WHERE t.team IN (g.home_team, g.away_team)
ORDER BY game_date DESC
) g
ORDER BY t.team;