2013-04-09 77 views
0

我想獲取每個人具有最大值的行。使用MySQL。SQL:每個組具有最大值的返回行

person  page  views 
John   home  20 
John   cart  15 
John   search  43 
James  home  32 
James  about  41 
Kim   cart  5 
Kim   contact 3 

結果

Person Page 
John  search 
James about 
Kim  cart  

一個想法是讓MAX(views) GROUP BY PERSON,然後做IF(a.views = b.max_views, page, 0)但是這似乎將需要3個步驟,有可能是一個更簡單的方法。

回答

1
Select * From table t 
where views = 
    (Select Max(views) From table 
     Where person = t.person) 
1

您可以使用子查詢得到的結果:

select t1.person, t1.page 
from yt t1 
inner join 
(
    select max(views) maxview, person 
    from yt 
    group by person 
) t2 
    on t1.person = t2.person 
    and t1.views = t2.maxview; 

SQL Fiddle with Demo

0

試試這個

select 
    * 
from 
    data d 
where d.views = (select max(views) from data d2 where d2.person = d.person) 
+1

不需要'd2'別名 – 2013-04-09 18:34:29

+0

@CharlesBretana燁,已習慣給查詢提供別名;) – Akash 2013-04-09 18:35:15

+0

d2不是別名f或查詢,它只是子查詢中的表data的別名。這不是必需的,因爲查詢處理器在查看當前查詢之外時,總是在當前查詢/子查詢的所有表中查找列。 – 2013-09-29 14:57:04