0

我正在尝试使用 SQL 提取以下信息。表的架构如下:

person_id、role_id、计数

例如表:

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。有人可以帮我弄这个吗?

4

2 回答 2

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
于 2013-06-25T11:10:24.250 回答
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

有其他方法,但这在两个数据库中都有效。

于 2013-06-25T11:07:38.737 回答