数据库
首页 > 数据库> > 如果MAX()等于当前行SUM()的聚合值,MySQL如何选择1?

如果MAX()等于当前行SUM()的聚合值,MySQL如何选择1?

作者:互联网

如果当前行的面积等于MAX(SUM(c.area)),我想选择一个名为sliced的新列(值可以为1/0或true / false无关紧要),即标记该行最高总价值:

SELECT p.name AS name, SUM(c.area) AS area
FROM City AS c
   INNER JOIN Province AS p ON c.province_id = p.id
      INNER JOIN Region AS r ON p.region_id = r.id
WHERE r.id = ?
GROUP BY p.id
ORDER BY p.name ASC

我尝试添加到选择区域=切片的MAX(面积)甚至面积=切片的SUM(MAX(c.area))面积,但是出现语法错误.我不得不承认我在SQL方面不是很好.谢谢.

解决方法:

这是仅对一个小组进行以下操作的方法:

set @row := 0;
select name, area, sliced
from (
    select name, area, (@row := @row + 1) = 1 as sliced
    from (
        SELECT p.name, SUM(c.area) AS area
        FROM City AS c
        INNER JOIN Province AS p ON c.province_id = p.id
        INNER JOIN Region AS r ON p.region_id = r.id
        WHERE r.id = ?
        GROUP BY 1
        ORDER BY 2 desc) t1
    ) t2
order by 1;

内部查询(t1)首先按总面积最大的分组和排序.
下一个查询(t2)为所切列的第一行赋予true值,其他所有行均为false.
外部查询按所需方式对行进行排序-按名称.

由于只有一个表扫描和分组依据,因此这应该非常有效.

标签:sum,aggregate-functions,max,sql,mysql
来源: https://codeday.me/bug/20191202/2086883.html