简体   繁体   English

如何从表中总结每个唯一的最后一个值

[英]How to sum each unique last value from table

I want to SUM the total amount of KG of each unique last value in a table.我想对表中每个唯一最后一个值的 KG 总量求和。

The table i currently have looks like this我目前的桌子看起来像这样

|----|-----------|----------|----------|----------|---------------|
| id | productId | amountKg | amountSt | location | datetimeStamp |
|----|-----------|----------|----------|----------|---------------|
| 12 | 19        | 201      | 0        | loc1     | 2019-12-21    |
| 13 | 19        | 35       | 0        | loc2     | 2019-12-22    |  <---
| 14 | 19        | 400      | 0        | loc1     | 2019-12-23    |  <---
|----|-----------|----------|----------|----------|---------------|

And I have this SQL query我有这个 SQL 查询

SELECT SUM(amountKg) FROM (SELECT amountKg FROM storage GROUP BY location ORDER BY id ASC) t;

Whe I run this query I get the result 236 The result I want is 435, the sum of the 14 and 13 (The arrows in the table)当我运行这个查询时,我得到了结果 236 我想要的结果是 435,14 和 13 的总和(表中的箭头)

Any help is appreciated任何帮助表示赞赏

Find first the ID's that have the latest row for each location and then sum those together:首先查找每个位置具有最新行的 ID,然后将它们相加:

select sum(s.amountKg)
from storage s
  join ( 
    select location, max(id) as id
    from storage
    group by location
  ) as latest on latest.id=s.id

See DB-FiddleDB-Fiddle

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

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