2015-11-13 97 views
-1

我試圖獲取每組中具有最大值的行。每個組的最大值的行

我有這個表

+-------+-----------+--------------+-----------+ 
| nid |  name | crated  | grp_id | 
+-------+-----------+--------------+-----------+ 
| 1 | RAND_NAME |  123  |  11 | 
| 2 | EHllo  |  111  |  11 | 
| 3 | Stop by |  444  |  11 | 
| 4 | Radr c |  555  |  11 | 
| 5 | NAE  |  666  |  22 | 
| 6 | ABC  |  1234  |  22 | 
| 7 | RAND  |  123  |  22 | 
| 8 | YELLO  |  444  |  22 | 
| 9 | AAA  |  555  |  33 | 
| 10 | WWW  |  1235  |  33 | 
| 11 | ADF  |  553  |  33 | 
+-------+-----------+--------------+-----------+ 

所以,我想這個表

+-------+-------------+------------+-----------+ 
| nid |  name | created | grp_id | 
+-------+-------------+------------+-----------+ 
| 3 | Stop by  | 555  |  11 | 
| 6 | ABC   | 1234  |  22 | 
| 10 | WWW   | 1235  |  33 | 
+-------+-------------+------------+-----------+ 

這意味着我要搶的是每個組中最高的創造價值的行。該表將按grp_id分組。

我是這樣想的:

SELECT nid, name, created, grp_id 
    FROM table t 
    WHERE t.created = (SELECT MAX(t1.created) FROM table t1) 
    GROUP BY grp_id 
    ORDER BY grp_id 

但是,它沒有發揮出來。我應該做些什麼來獲得每組中具有最高創造價值的三個不同的行?

感謝您瞭解我的糟糕解釋。

+2

爲什麼是444> 555 GRP 11? – Sentinel

+0

對不起,錯誤。改變了價值。 – PHG

回答

0

你需要一個子查詢:

SELECT yourtable.* 
FROM yourtable 
LEFT JOIN (
    SELECT grp_id, MAX(created) AS max 
    FROM yourtable 
    GROUP BY grp_id 
) AS maxgroup ON (
    (yourtable.grp_id = maxgroup.grp_id) AND (yourtable.created = maxgroup.max) 
) 

子查詢中獲得各組的ID /最大值,並且父/外部查詢聯接agains子選擇的結果,以獲得其餘字段爲行( s)最大值出現在上面。

+0

爲什麼''在'inner join'上留下了'join'? –

+0

我的習慣的力量。我寫的大部分查詢往往是左連接。在這種情況下無關緊要,因爲您知道數據將在雙方都可用,因爲「雙方」具有相同的源數據。 –

0

嘗試:

SELECT nid, name, MAX(created), grp_id FROM t GROUP BY grp_id; 
+0

這可能適用於'mySql',但距離ANSI SQL很遠 –

0
SELECT nid, name, MAX(created), grp_id 
FROM table 
GROUP BY grp_id 
order by MAX(nid);