【问题标题】:mysql finding the sum of subgroup maximumsmysql查找子组最大值的总和
【发布时间】:2018-12-27 02:52:03
【问题描述】:

如果我在 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

...有没有办法找到每个type 的最新dates 对应的amounts 的总和?对于任何给定的type,保证没有重复的dates。

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

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

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

谢谢!

【问题讨论】:

    标签: mysql django orm


    【解决方案1】:

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

    【讨论】:

    • 这些都是难以置信有用的例子...谢谢!我显然需要更加熟悉语法,特别是对于连接,因为我仍然不确定 why 您的第一个示例是否适用于“b.type is null”部分(尽管它显然确实得到了正确的答案)。再次感谢您如此彻底的回复。
    猜你喜欢
    • 2017-08-22
    • 2018-12-28
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多