2012-12-20 50 views
1

这是我现在在我的查询:MySQL的:选择MAX值和分组

+--------------------+-----------+------------+ 
| status    | entity_id | seconds | 
+--------------------+-----------+------------+ 
| Submitted   |  494 | 1352102400 | 
| Accepted   |  494 | 1352275200 | 
| In press/e-publish |  494 | 1352966400 | 
| Rejected   |  520 | 1355817600 | 
| Accepted   |  570 | 1352102400 | 
+--------------------+-----------+------------+ 

我希望它看起来像:

+--------------------+-----------+------------+ 
| status    | entity_id | seconds | 
+--------------------+-----------+------------+ 
| In press/e-publish |  494 | 1352966400 | 
| Rejected   |  520 | 1355817600 | 
| Accepted   |  570 | 1352102400 | 
+--------------------+-----------+------------+ 

在准SQL:

SELECT status, entity_id, MAX(seconds) 
FROM foo 
GROUP BY entity_id, seconds 

上面的准SQL看起来是正确的,但“状态”列值不对应正确的行。我得到类似的东西在下面:

+--------------------+-----------+------------+ 
| status    | entity_id | seconds | 
+--------------------+-----------+------------+ 
| Submitted   |  494 | 1352966400 | 
| Rejected   |  520 | 1355817600 | 
| Accepted   |  570 | 1352102400 | 
+--------------------+-----------+------------+ 

回答

6

未经检验的,而应该是这个样子:

SELECT status, entity_id, seconds 
FROM entities E 
WHERE E.seconds == (
    SELECT MAX(E2.seconds) 
    FROM entities E2 
    WHERE E2.entity_id = E.entity_id 
) 

(设置为你的问题SQLfiddle会给你一个更测试了答案:P)

+0

直到现在还没有听说过SQL小提琴。幸运的是,下面的海报为我们创建了SQL Fiddle页面(http://sqlfiddle.com/#!2/e6ab2/12),并且我能够测试您的查询,并且它的工作原理除了“==”,课程。 :) – user785179

+0

Doh!这是一个非常愚蠢的错误,使... ...(脸红)特别是因为我有正确的三行下来。 – Amadan

2

下面的查询会给你预期的结果。

SELECT max(maxsec), status, entity_id from 
(SELECT status, entity_id, MAX(seconds) as maxsec 
FROM table1 
GROUP BY entity_id,status) a GROUP BY entity_id 

您的架构已创建here

+1

感谢您创建SQLFiddle页面。这是非常有用的,你的查询工作。 – user785179