mysql - Mysql双聚合函数

标签 mysql count sum

我想从一系列返回值中获取最大值,但我无法找到一个简单的方法来做到这一点。我的查询返回所有行,所以 1/2 在那里。我可以用 PHP 过滤它,但我想用 SQL 来完成这一切。我尝试使用 max子查询,但仍然返回所有结果。

DDL:

create table matrix(
   count int(4), 
   date date, 
   product int(4)
);
create table products(
   id int(4), 
   section int(4)
);

DML:

select max(magic_count), section, id
from (
    select sum(count) as magic_count, p.section, p.id
    from matrix as m
    join products as p on m.product = p.id
    group by m.product
) as faketable
group by id, section

Demo with my current try.

仅 ID 13应该从样本数据中返回,因为它们具有最高的累积 count对于每个 section s。

Here's a second SQL fiddle that demonstrates the same issue.

最佳答案

给你:

select a.id, 
       a.section,
       a.magic_count
from (
    select p.id,
           p.section,
           magic_count
    from (
        select m.product, sum(count) as magic_count
        from matrix m
        group by m.product
    ) sm
    join products p on sm.product = p.id
) a
left join (
    select p.id,
           p.section,
           magic_count
    from (
        select m.product, sum(count) as magic_count
        from matrix m
        group by m.product
    ) sm
    join products p on sm.product = p.id
) b on a.section = b.section and a.magic_count < b.magic_count
where b.id is null

关于mysql - Mysql双聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121436/

相关文章:

mysql - laravel where子句中的子查询

mysql - 如何向我的 SQL 查询添加 NOT 子句

SQL 计数和求和

PHP基于数组计算几列的总和

mysql - 在单个查询中查找各种表中的总记录

php - MYSQL 创建动态查询(数据透视)

javascript - 从我的本地主机获取数据并将其显示在屏幕上?

mysql - 多重连接 Mysql 将 SUM 值加倍

mysql - 连接 2 表 Mysql 的查询中的计算

c - 将 int 与 char 数组相加