我试图运行以下查询:对于每种类型的视频游戏,打印产生该类型最多游戏的年份。我有两张桌子:
游戏:id,name,year
Game_Types:game_id,type
游戏看起来像这样:
id name year
1 The First 2005
2 The Second 2006
3 The Third 2005
4 Fourth 2008
5 Sweetness 2008
Game_Types如下所示:
game_id type
1 action
2 fps
3 animated
3 action
4 stealth
5 stealth
5 action
到目前为止,我有一个查询生成每种类型的最大数量,如下所示:
SELECT TYPE, max(cnt)
FROM (
SELECT GT.GENRE, G.YEAR, COUNT(*) AS cnt
FROM GAMES G, GAME_TYPES GT
WHERE G.ID = GT.GAME_ID
GROUP BY GT.TYPE, G.YEAR
)
GROUP BY TYPE;
但是,这会生成如下表格:
TYPE MAX(cnt)
Animated 42
Mystery 58
我无法弄清楚如何将年份合并到结果中并从我的选择中移除max(cnt)。我尝试了下面的内容,但这不起作用。
SELECT TYPE, YEAR, max(cnt)
FROM (
SELECT GT.GENRE, G.YEAR, COUNT(*) AS cnt
FROM GAMES G, GAME_TYPES GT
WHERE G.ID = GT.GAME_ID
GROUP BY GT.TYPE, G.YEAR
)
GROUP BY TYPE;
我觉得我错过了一些简单的思考过程,所以非常感谢任何帮助!
答案 0 :(得分:2)
您可以将row_number()
用于此目的:
SELECT GENRE, YEAR, CNT
FROM (SELECT GT.GENRE, G.YEAR, COUNT(*) AS cnt,
ROW_NUMBER() OVER (PARTITION BY GT.GENRE ORDER BY COUNT(*) DESC) as seqnum
FROM GAMES G JOIN
GAME_TYPES GT
ON G.ID = GT.GAME_ID
GROUP BY GT.GENRE, G.YEAR
)
WHERE seqnum = 1;
答案 1 :(得分:0)
您可以使用此代码
选择类型,年份 (从游戏,game_types中选择类型,年份,计数(games.id)作为cnt 其中id = game_id group by year,type) 作为具有max(cnt)
的类型的组希望这能解决您的问题。