繁体   English   中英

双聚合函数Mysql

[英]Double Aggregate Function Mysql

我想从一系列返回值中获取最大值,但是我无法弄清楚这样做的简单方法。 我的查询以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和ID 3因为ID对于每个s section具有最高的累计count

这是第二个SQL小提琴,它演示了相同的问题。

干得好:

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

在这里,您无需使用JOIN即可获得解决方案,它的性能要优于使用许多JOIN的其他答案:

select @rn := 1, @sectionLag := 0;

select id, section, count from (
    select id,
           case when @sectionLag = section then @rn := @rn + 1 else @rn := 1 end rn,
           @sectionLag := section,
           section, 
           count
    from (
        select id, section, sum(count) count
        from matrix m
        join products p on m.product = p.id
        group by id, section
    ) a order by section, count desc
) a where rn = 1

开头的变量用于模仿窗口函数( LAGROW_NUMBER ),这些函数在MySQL 8.0或更高版本中可用(如果您使用的是这样的版本,请告诉我,所以我还将为您提供窗口函数的解决方案)。

演示

另一个演示 ,您可以在其中比较my查询和另一个查询的性能。 它包含约2万行,而我的查询往往快将近2倍。

暂无
暂无

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

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