mysql查找子组最大值的总和

时间:2018-07-19 05:00:50

标签: mysql django orm

如果我在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相对应的type的总和?对于任何给定的date,保证没有重复的type

我希望从上面的数据中得到的答案可能像这样分解:

  • date 1的最新type是2018-02-01,其中amount是50;
  • date 2的最新type是2018-04-01,其中amount是4000;
  • date最近的type是2018-06-01,其中amount是1;
  • 50 + 4000 +1 = 4051

有没有一种方法可以在单个查询中直接到达4051?这适用于使用MySQL的Django项目,如果有区别的话;我也找不到与ORM相关的解决方案,因此认为原始SQL查询可能是一个更好的起点。

谢谢!

1 个答案:

答案 0 :(得分:3)

不确定对于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

Demo

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

Demo

或通过使用相关的字幕

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

Demo

对于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;

Demo

相关问题