如何获取另一列具有最大值的行中的列值?

时间:2013-06-25 04:36:46

标签: mysql sql select group-by where

我有一个包含三个字段user_namepagen_loads的表格。我希望按user_name对表进行分组,为每个用户名显示最大负载数和与此(最大)负载数对应的页面。我可以在一个MySQL子句中完成吗?

1 个答案:

答案 0 :(得分:3)

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  username, MAX(n_loads) n_loads
            FROM    tableName 
            GROUP   BY username
        ) b ON  a.username = b.username AND
                a.n_loads = b.n_loads

SELECT  a.*
FROM    tableName a
WHERE   n_loads = 
        (SELECT MAX(b.n_loads)
        FROM    tableName b
        WHERE   a.username = b.username);