2012-12-20 48 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