我有一张桌子,我想要得到:
ID Name Stock Code Date
<---------------------------------------------->
123 GAME_0011 1 WK1 2018-11-20 16:12:16
120 GAME_0088 212 WK1 2018-11-20 19:32:13
109 GAME_0088 21 WK1 2018-11-20 19:32:13
101 GAME_0088 20 WK1 2018-11-20 14:00:41
105 GAME_0011 1 WK1 2018-11-20 14:00:41
102 GAME_0088 2 WK1 2018-11-20 14:00:41
结果将是按名称,代码以及每个date
字段的最大值,如果日期相同,也将按id
进行过滤:
ID Name Stock Code Date
<---------------------------------------------->
120 GAME_0088 212 WK1 2018-11-20 19:32:13
123 GAME_0011 1 WK1 2018-11-20 16:12:16
我的查询是:
SELECT *
FROM games
WHERE name IN ('GAME_0088', 'GAME_0011')
AND code IN ('WK1')
AND date IN (SELECT max(date) FROM stocks GROUP BY name)
ORDER BY id desc
但是返回:
ID Name Stock Code Date
<---------------------------------------------->
123 GAME_0011 1 WK1 2018-11-20 16:12:16
109 GAME_0088 21 WK1 2018-11-20 19:32:13
怎么了?我也该如何通过MAX ID进行过滤?
答案 0 :(得分:3)
在派生表中,可以为ID
和name
的特定组获取code
的最大值。使用此信息重新加入games
表,以获取对应于最大日期的行。
SELECT g.*
FROM games AS g
JOIN
( SELECT name, code, MAX(ID) AS max_id
FROM games
GROUP BY name, code
) AS dt ON dt.name = g.name AND
dt.code = g.code AND
dt.max_id = g.ID
WHERE g.name IN ('ACK1134', 'ACK1159')
AND g.code IN ('CD23')
ORDER BY g.ID desc