总结不同的MySQL记录

时间:2017-09-11 22:52:37

标签: mysql sum distinct

我有一个库存计数表,需要对每个位置的每个项目求和。 所以计数表基本上是一个计数日志

+-----------+---------+---------+-------------+---------------------+
| record_id | item_id | count   | location_id | time_stamp          |
+-----------+---------+---------+-------------+---------------------+
|         1 |     129 |    3.00 |           1 | 2017-08-23 16:56:05 |
|         2 |     129 |   14.00 |           2 | 2017-08-23 16:57:28 |
|         3 |     129 |    4.00 |           1 | 2017-08-31 16:59:39 |
|         4 |     129 |   14.00 |           2 | 2017-08-31 17:01:27 |
|         5 |     133 |    4.00 |           1 | 2017-08-23 17:02:21 |
|         6 |     133 |    0.00 |           2 | 2017-08-23 17:03:22 |
|         7 |     133 |    8.00 |           3 | 2017-08-23 17:03:55 |
|         8 |     133 |    4.00 |           1 | 2017-08-26 17:04:22 |
|         9 |     133 |    1.00 |           2 | 2017-08-26 17:05:08 |
|        10 |     133 |    9.00 |           3 | 2017-08-26 17:05:44 |
+-----------+---------+---------+-------------+---------------------+

因此,项目129共有18个。它首先计入8/23,但最近8/31的计数显示位置1中的4个和位置2中的14个。所以我需要的是总数(总和)根据最近的计数,所有地点的每个项目。

2 个答案:

答案 0 :(得分:1)

不确定这是否是您想要的,您应该在OP中发布您的预期结果,然后我们可以准确地为您提供您想要的内容。

您可以尝试以下sql:

select
    t1.`item_id`,
    sum(t1.`count`) sum_count
from yourtable t1
inner join (
    select `item_id`, `location_id`, max(`time_stamp`) `time_stamp`
    from yourtable
    group by `item_id`, `location_id`
) t2
on t1.`item_id` = t2.`item_id`
and t1.`location_id` = t2.`location_id`
and t1.`time_stamp` = t2.`time_stamp`
group by t1.`item_id`

请参阅SQLFiddle中的 DEMO

答案 1 :(得分:0)

具有相关子查询的解决方案:

SELECT t1.item_id, SUM(t1.count)
FROM Table1 t1
WHERE t1.time_stamp =  
      (SELECT MAX(t11.time_stamp) 
       FROM Table1 t11
       WHERE t1.item_id=t11.item_id AND  t1.location_id=t11.location_id)
GROUP BY t1.item_id

Fiddle