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

How to get the value of max() group when in subquery?

所以我想找到其他组中平均年龄最大的组的部门名称或部门 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

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

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

我拍摄了我认为你正在寻找的东西。以下将为您提供平均年龄最高的部门分支。我假设 department_branch table 有一个 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

你可以试试这个..

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 做了一些更改,将部门名称放在 "department" 字序 table.. 所以,根据需要加入 table 加号,然后我更改了您的查询,最终如果在 branch_department table 中放置了部门名称(但我不这么认为),您可以将字段及其处理添加到您的查询中

更新

补充说,如果您想避免相同的平均情况,您可以通过以这种方式附加一个 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
;