简体   繁体   English

MySQL sum case value 等于该组的最大值

[英]MySQL sum case value equals max value of that group

I'm trying to solve this query to return the total count of items in a group and the total of items in that group which value equals the max value of one field of that group and also which is the max(value).我正在尝试解决此查询以返回组中项目的总数以及该组中项目的总数,其中值等于该组中一个字段的最大值,也是最大值(值)。

So far:到目前为止:

SELECT
    limid, COUNT(*), SUM(CASE WHEN cotavertical=MAX(cotavertical) THEN 1 ELSE 0 END), MAX(cotavertical)
FROM limites
LEFT JOIN tbparentchild ON parent=limid
LEFT JOIN tbspatialbi ON child=rgi
WHERE limtipo=4 AND x=1
GROUP BY limid

So far MySQL returns到目前为止 MySQL 返回

"Invalid use of group function." “无效使用组功能。”

Is it too complex to solve in MySQL only?仅在 MySQL 中解决是否太复杂? Better to use algorithm?更好地使用算法?

You are trying to use the max value for each group in an aggregate function ( SUM ) before the aggregation has finished, and hence it is not available.您试图在聚合完成之前使用聚合函数 ( SUM ) 中每个组的最大值,因此它不可用。 The query below uses the strategy of joining a subquery which contains the max value of cotavertical for each limid group.下面的查询使用加入包含每个limid组的cotavertical最大值的子查询的策略。 In this case, the max value per group which you want to use will now be available from another source, and you can sum using it.在这种情况下,您要使用的每个组的最大值现在可以从另一个来源获得,您可以使用它进行求和。

SELECT l.limid,
       COUNT(*),
       SUM(CASE WHEN cotavertical = t.cotamax THEN 1 ELSE 0 END),
       MAX(cotavertical)
FROM limites l
LEFT JOIN tbparentchild pc
    ON pc.parent = l.limid
LEFT JOIN tbspatialbi s
    ON pc.child = s.rgi
LEFT JOIN
(
    SELECT limid, MAX(cotavertical) AS cotamax
    FROM limites
    LEFT JOIN tbparentchild
        ON parent = limid
    LEFT JOIN tbspatialbi
        ON child = rgi
    WHERE limtipo = 4 AND x = 1
    GROUP BY limid
) t
    ON l.limid = t.limid
WHERE limtipo = 4 AND l.x = 1
GROUP BY l.limid

Another option for solving your problem would be to use a subquery directly in the CASE statement.解决问题的另一种选择是直接在CASE语句中使用子查询。 But, given the size and number of joins in your original query, this would be way uglier than the query above.但是,考虑到规模和数量在联接您的原始查询,这将是丑陋的方式比上面的查询。 MySQL does not support common table expressions, which would have helped with both these solutions. MySQL 不支持公共表表达式,这对这两种解决方案都有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM