mysql求子群最大值之和

cygmwpex  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(326)

如果mysql中有下表:

date        type amount
2017-12-01  3    2
2018-01-01  1    100
2018-02-01  1    50
2018-03-01  2    2000
2018-04-01  2    4000
2018-05-01  3    2
2018-06-01  3    1

……有没有办法找出 amount 对应于最新的 date 每个的s type ? 保证不重复 date 对于任何给定的 type .
我希望从上述数据中得到的答案可以分解如下:
最新的 date 为了 type 1为2018-02-01,其中 amount 为50;
最新的 date 为了 type 2是2018-04-01 amount 为4000;
最新的 date 为了 type 3是2018-06-01 amount 为1;
50 + 4000 + 1 = 4051
有没有办法在一次查询中直接到达4051?这是针对使用mysql的django项目的,如果这有区别的话;我也找不到与orm相关的解决方案,所以我认为原始sql查询可能是一个更好的开始。
谢谢!

yshpjwxd

yshpjwxd1#

对于django不确定,但在原始sql中,可以使用自连接根据最新日期为每种类型选取最新行,然后聚合结果以获得每种类型的金额总和

select sum(a.amount)
from your_table a
left join your_table b on a.type = b.type
and a.date < b.date
where b.type is null

演示
或者

select sum(a.amount)
from your_table a
join (
  select type, max(date) max_date
  from your_table
  group by type
) b on a.type = b.type
and a.date = b.max_date

演示
或者使用相关子查询

select sum(a.amount)
from your_table a
where a.date =  (
  select max(date) 
  from your_table
  where type = a.type
)

演示
对于mysql 8,您可以使用窗口函数获得所需的结果

select sum(amount)
from (select *, row_number() over (partition by type order by date desc) as seq
      from your_table 
     ) t
where seq = 1;

演示

相关问题