我正在使用本地mysql服务器,并且有两个表。
表A:
ID | Name
1 Joe
2 Bob
3 John
表B:
ID | DATE | Name_ID | Point
1 2010-01-01 1 1
2 2011-01-01 1 1
3 2013-01-01 1 -1
4 2010-01-01 2 -1
5 2012-01-01 2 -1
6 2013-01-01 2 -1
7 2014-01-01 2 1
对于表A中的每个ID,我正在尝试获取
想要的结果:
Name | Latest_Date | Point_total
John NULL NULL
Joe 2013-01-01 1
Bob 2014-01-01 -2
到目前为止,我有这个查询:
SELECT DISTINCT a.Name, b.Date, SUM(b.point) OVER (PARTITION BY b.Name_ID) Point_total FROM
TableA a
LEFT OUTER JOIN TableB b
ON a.ID = b.Name_ID
INNER JOIN (
SELECT b.Name_ID, MAX(b.Date) Latest_Date
FROM TableB b GROUP BY b.Name_ID ) m
ON (m.Latest_Date = b.Date or (b.Date is NULL)) AND
(b.Name_ID = m.Name_ID OR (b.Name_ID is NULL))
ORDER BY Name_ID;
结果表确实输出了正确的最大日期,但是运行总计仅考虑了具有最大日期的条目点。
我在这里想念什么?
这看起来像聚合:
SELECT a.Name, MAX(b.Date), SUM(b.point) as Point_total
FROM TableA a LEFT OUTER JOIN
TableB b
ON a.ID = b.Name_ID
GROUP BY a.name
这是一个聚合查询:
select a.name, max(b.date) latest_date, sum(b.point) point_total
from a
left join b on b.name_id = a.id
group by a.id, a.name
SELECT A.Name, MAX(B.Date) as Max_Date, SUM(b.point) as Total_Points
FROM TableA as A
LEFT JOIN TableB as B
ON A.ID = B.Name_ID
GROUP BY A.name