[英]MySQL - Return Latest Date and Total Sum from two rows in a column for multiple entries
[英]MySQL get the SUM of a column ONLY from the latest date
我有一张这样的表:
---------------------------------------
| id | name | points | date |
---------------------------------------
| 1 | ana | 1 | 2014-12-10 |
| 2 | tom | 3 | 2015-12-09 |
| 3 | jim | 1 | 2013-12-02 |
| 4 | ana | 9 | 2014-12-10 |
| 5 | tom | 3 | 2015-12-09 |
| 6 | jim | 1 | 2016-12-08 |
| 7 | jim | 5 | 2016-12-08 |
| 8 | ana | 2 | 2016-12-08 |
| 9 | ana | 1 | 2016-12-08 |
| 10 | tom | 2 | 2013-12-07 |
-------------------------------------
在这个表中,我有一组名称。 这些名称可能在同一日期有不同点的重复条目。 他们也有不同日期的重复条目。 日期都不同,它们没有规律。
我的目标是返回以下内容:
name, SUM(points) WHERE MAX(date) for the name group
所以基本上我当前的查询是:
SELECT name, SUM(points) FROM table GROUP BY name;
但是,我需要它来仅从该名称组的最新日期开始计算名称组中的点条目,而不是将所有日期的所有点相加。
我怎样才能做到这一点?
要聚合每个名称的最新date
,您可以加入生成MAX(date)
的子查询,加入来自外部表和子查询的name
和date
。 这允许您为该组SUM()
。
SELECT
t.name,
SUM(points) AS total_points,
max_date
FROM
`table` t
JOIN (
-- Subquery produces latest date per name
SELECT
name,
MAX(date) AS max_date
FROM `table`
GROUP BY name
) name_dates
-- Join table to subquery on both name and the aggregate date
ON t.name = name_dates.name AND t.date = max_date
-- Group for the outer SUM()
GROUP BY t.name, max_date
这产生了结果:
+------+--------------+---------------------+
| name | total_points | max_date |
+------+--------------+---------------------+
| ana | 3 | 2016-12-08 00:00:00 |
| jim | 6 | 2016-12-08 00:00:00 |
| tom | 6 | 2015-12-09 00:00:00 |
+------+--------------+---------------------+
这是在行动。 http://sqlfiddle.com/#!9/dece38/1(sqlfiddle现在出现故障,可能需要重新粘贴查询以重新执行)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.