我想从一系列返回值中获取最大值,但我无法找到一个简单的方法来做到这一点。我的查询返回所有行,所以 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
仅 ID 1
和3
应该从样本数据中返回,因为它们具有最高的累积 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
请参阅 The Rows Holding the Group-wise Maximum of a Certain Column 的手册条目中的简化示例(和其他方法)
查看它的实时运行 here
关于mysql - Mysql双聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52121436/