SQL Keep running count, after inner Join
Posted
技术标签:
【中文标题】SQL Keep running count, after inner Join【英文标题】: 【发布时间】:2020-07-13 20:49:07 【问题描述】:我正在使用本地 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,我正在尝试获取
-
最大日期和
他们的分数的运行计数。 (日期和点在表 B 中)。
想要的结果:
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;
结果表确实输出了正确的最大日期,但运行总计仅考虑了具有最大日期的条目点。
我在这里错过了什么?
【问题讨论】:
这似乎与“运行总数”无关。 【参考方案1】:这看起来就像聚合:
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
【讨论】:
【参考方案2】:这是一个聚合查询:
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
【讨论】:
【参考方案3】: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
【讨论】:
以上是关于SQL Keep running count, after inner Join的主要内容,如果未能解决你的问题,请参考以下文章