如何在子查询中获取max()组的值?

时间:2016-06-13 13:58:37

标签: mysql sql mysql-workbench mysqldump

所以我想找到另一组中具有最大平均年龄的组的部门名称或部门ID(dpmid),这是我的查询:

select 
 MAX(avg_age) as 'Max average age' FROM (
    SELECT 
      AVG(userage) AS avg_age FROM user_data GROUP BY 
         (select dpmid from department_branch where 
            (select dpmbid from user_department_branch where 
               user_data.userid = user_department_branch.userid)=department_branch.dpmbid)
) AS query1

此代码仅显示平均年龄的最大值,当我尝试显示该组的名称时,它将显示错误的组名。

那么,如何显示来自另一个表的子查询的最大组名称???

2 个答案:

答案 0 :(得分:0)

我拍了一下我认为你正在寻找的东西。以下将为您提供平均年龄最高的部门分支。我假设department_branch表有一个department_name字段。您可能需要额外的加入才能获得该部门。

SELECT db.department_name, udb.dpmid, AVG(userage) as `Average age`

FROM   user_data as ud

       JOIN user_department_branch as udb
       ON udb.userid = ud.userid

       JOIN department_branch as db
       ON db.dpmbid = udb.dpmbid

GROUP BY udb.dpmid

ORDER BY `Average age` DESC

LIMIT 1

答案 1 :(得分:0)

你可以试试这个..

select MAX(avg_age) as max_avg, SUBSTRING_INDEX(MAX(avg_age_dep),'##',-1)  as max_age_dep from
(
    SELECT 
     AVG(userage) as avg_age, CONCAT( AVG(userage), CONCAT('##' ,department_name)) as avg_age_dep
     FROM user_data 
     inner join user_department_branch 
            on user_data.userid = user_department_branch.userid
     inner join department_branch 
            on department_branch.dpmbid = user_department_branch.dpmbid
     inner join department
            on department.dpmid = department_branch.dpmid
     group by department_branch.dpmid
) tab_avg_age_by_dep
;

我已经对ipothesys进行了一些更改,即部门名称放在"部门" anagraphical table ..所以,因为它需要加入一个表加上,然后我改变了你的查询,最终如果在branch_department表中放置了部门名称(但我不是这样)你可以添加字段及其对您的查询的处理

更新

如上所述,如果您想要避免相同的平均情况,您可以通过以这种方式附加rownum id来进一步明确平均值:

select MAX(avg_age) as max_avg, SUBSTRING_INDEX(MAX(avg_age_dep),'##',-1)  as max_age_dep from
(
    SELECT 
     AVG(userage) as avg_age, CONCAT( AVG(userage), CONCAT('##', CONCAT( @rownum:=@rownum+1, CONCAT('##' ,department_name)))) as avg_age_dep
     FROM user_data 
     inner join user_department_branch 
            on user_data.userid = user_department_branch.userid
     inner join department_branch 
            on department_branch.dpmbid = user_department_branch.dpmbid
     inner join department
            on department.dpmid = department_branch.dpmid
     ,(SELECT @rownum:=0) r 
     group by department_branch.dpmid
) tab_avg_age_by_dep
;