如何计算 mysql 中每组最后一行的总和

How to calculate sum of each group last row in mysql

vehicle_assignment_history

id    companyAccountId          date           totalVan     totalBike
1            4           2021-11-11 00:00:00     2             0
2            4           2021-11-11 00:00:00     3             0
3            4           2021-11-11 00:00:00     1             0        
4            8           2021-11-11 00:00:00     1             0
5            8           2021-11-12 00:00:00     2             0        
6            9           2021-11-13 00:00:00     0             2
7            9           2021-11-14 00:00:00     0             1        

我想计算每个组最后一行的总和companyAccountId。还有一个范围内的日期。

例如:- 2021-11-11 -> 2021-11-13

   totalVan              totalBike
1 + 2 + 0 = 3           0 + 0 + 2 = 2

2021-11-11 -> 2021-11-14

   totalVan              totalBike
1 + 2 + 0 = 3           0 + 0 + 1 = 1

SELECT 公司账号, sum(totalVan) AS [货车总数], sum(totalBike) AS [自行车总数], 来自 vehicle_assignment_history 按公司帐户 ID 分组 HAVING '2021-11-11' < date AND date < '2021-11-13'

一种方法是获取一个复杂字符串的最大值(对于每个 companyAccountId),该字符串将 id 和您要查找的最高 id 的字段连接起来,然后从末尾提取您想要的字段,然后将其转换回数字(全部在子查询中,因此您可以对所有结果值求和)

select sum(latestTotalVan) as totalVan, sum(latestTotalBike) as totalBike
from (
    select
        cast(substring(max(concat(lpad(id,11,'0'),totalVan)) from 12) as unsigned) latestTotalVan,
        cast(substring(max(concat(lpad(id,11,'0'),totalBike)) from 12) as unsigned) latestTotalBike
    from vehicle_assignment_history
    where date between '2021-11-11 00:00:00' and '2021-11-14 00:00:00'
    group by companyAccountId
) latest_values

fiddle

mysql 8 添加window 功能,使这种事情变得更加容易。