SQL组通过返回错误的数据

时间:2012-06-10 15:09:40

标签: mysql sql group-by

这让我发疯了!冥想MySQL DBMS(抱歉不指定)...

我有以下表格:

"id", "pingdate", "players"
"3","2012-05-24 11:45:04","63"
"1","2012-05-24 12:15:03","14"
"2","2012-05-24 12:15:03","38"
"3","2012-05-24 12:15:03","24"
"1","2012-05-24 12:45:04","22"
"2","2012-05-24 12:45:04","40"
"3","2012-05-24 12:45:04","66"
"1","2012-05-24 13:15:03","14"
"5","2012-05-24 13:15:03","99"
"3","2012-05-24 13:15:03","63"
"3","2012-05-24 13:15:03","38"
"4","2012-05-24 13:15:03","63"

我想要以下结果:

"5","2012-05-24 13:15:03","99"
"3","2012-05-24 12:45:04","66"
"4","2012-05-24 13:15:03","63"

在文字中,我想要3个不同的ID,最高的玩家和正确的pingdate。

我试过这个,但它返回了错误的pingdate:

SELECT id, 
       pingdate, 
       max(players) AS players 
FROM pings 
GROUP BY id  
ORDER BY players DESC 
LIMIT 3

4 个答案:

答案 0 :(得分:1)

您没有指定DBMS,因此这是一个ANSI SQL解决方案:

select *
from (
    select id, 
           pingdate,
           rank() over (partition by id order by players desc) as rnk
    from pings
) t
where rnk <= 3
order by players desc

答案 1 :(得分:0)

您必须使用联接或子查询来执行此操作,请参阅sql - getting the id from a row based on a group by

Select  a.id, a.pingdate, a.players from pings a, (
  SELECT id, max(players) AS players 
  FROM pings 
  GROUP BY id ) b 
where a.id=b.id and a.players=b.players 
ORDER BY players DESC 
LIMIT 3

答案 2 :(得分:0)

首先,您需要返回所有结果....然后返回3

SELECT *
FROM (
SELECT id,pingdate, max(players) AS players 
FROM pings 
GROUP BY id, pingdate  )
WHERE rownum = 3
ORDER BY players DESC 

我希望这会对你有所帮助

答案 3 :(得分:0)

maximal的定义:=没有更高的值:

SELECT id, pingdate, players 
FROM pings pi
    WHERE NOT EXISTS (
         SELECT *
         FROM pings nx
         WHERE nx.id = pi.id
         AND nx.players > pi.players
         )
ORDER BY players
LIMIT 3
    ;