查找具有最大计数的每个people_id对应的role_id

时间:2013-06-25 10:47:59

标签: mysql sql database oracle

我正在尝试使用SQL提取以下信息。 该表的模式如下:

person_id,role_id,count

例如表:

p1, r1, 5
p1, r2, 3
p2, r1, 8
p1, r3, 7
p2, r2, 3
p3, r1, 10
p3, r2, 15

我想编写查询来为每个people_id提取具有最大计数的role_id。我怎么能在MYSql或oracle DB

中做到这一点

对于上表,输出应如下所示

p1, r3, 7
p2, r2, 8
p3, r2, 15

以上输出的说明:

p1 has the maximum count as r3 i.e. 7  
p2 has maximum count as r2 i.e. 8  
p3 has maximum count as r2 i.e.15  

我无法找出提取此数据的SQL。有人可以帮我弄这个吗?

2 个答案:

答案 0 :(得分:0)

一种方式是聚合和加入:

select t.person_id, t.role_id, t.count
from t join
     (select person_id, max(count) as count
      from t
      group by person_id
     ) tsum
     on tsum.person_id = t.person_id and
        tsum.count = t.count;

但是,如果重复项具有相同的最大计数,则会出现问题。

如果你想要一个任意角色,当有重复时,你可以从这个查询聚合结果:

select t.person_id, max(t.role_id), t.count
from (select t.person_id, t.role_id, t.count
      from t join
           (select person_id, max(count) as count
            from t
            group by person_id
           ) tsum
           on tsum.person_id = t.person_id and
              tsum.count = t.count
     ) t
group by t.person_id, t.count

还有其他方法,但这适用于两个数据库。

答案 1 :(得分:0)

忽略列名称被称为count(更好地使用在任何SQL风格中都不可能是保留字的东西): -

SELECT a.person_id, a.role_id, a.count
FROM table a
INNER JOIN 
(
    SELECT person_id, MAX(count) AS MaxCount
    FROM table
    GROUP BY person_id
) Sub1
ON a.person_id = Sub1.person_id AND a.count = Sub1.MaxCount