我有以下情况:
我想使用tableB
的评分更新tableA
。挑战是:收视率随机变化,当更新tableB的记录时,我考虑了比赛的日期,如果评级发生变化,让我们在星期二说,比赛是在星期一之前,我希望评级为以前的评级不是最新评分。
#table A: contains rating of players, changes randomly at any date depending
#on drop of form from the players
PID| Rating | DateChange |
1 | 2 | 10-May-2014 |
1 | 4 | 20-May-2015 |
1 | 20 | 1-June-2015 |
2 | 4 | 1-April-2014|
3 | 4 | 5-April-2014|
2 | 3 | 3-May-2015 |
#Table B: contains match sheets. Every player has a different match sheet
#and plays different dates.
MsID | PID | MatchDate | Win | Rating |
1 | 2 | 10-May-2014 | No | 0 |
2 | 1 | 15-May-2015 | Yes | 0 |
3 | 3 | 10-Apr-2014 | No | 0 |
4 | 1 | 21-Apr-2015 | Yes | 0 |
5 | 1 | 3-June-2015 | Yes | 0 |
6 | 2 | 5-May-2015 | No | 0 |
#I am trying to achieve this by running the ms-access query: i want to get
#every players rating at the time the match was played not his current
#rating.
MsID | PID | MatchDate | Rating |
1 | 2 | 10-May-2014 | 4 |
2 | 1 | 15-May-2015 | 2 |
3 | 3 | 10-Apr-2014 | 4 |
4 | 1 | 21-Apr-2015 | 2 |
5 | 1 | 3-June-2015 | 20 |
6 | 2 | 5-May-2015 | 3 |
我尝试了以下代码:
Update [B-table] as wdev
set wdev.rating = ( SELECT B.MsID, B.PID, B.MatchDate, A.rating as Rating
FROM [B-table] B
INNER JOIN [A-table] A
on B.PID = A.PID
INNER JOIN (
SELECT MAX(Y.DateChange) MDC, Y.PID, Z.Matchdate
FROM [B-table] Z
INNER Join [A-table] Y
on Z.PID = Y.PID
and Y.DateChange <= Z.MatchDate
GROUP BY Y.PID, Z.Matchdate) C
on C.mdc = A.DateChange
and A.PID = C.PId
and B.MatchDate = C.Matchdate) And B.MsID = Wdev.MsID
总结:我希望评分对应于匹配日期或之前的最大日期更改。
答案 0 :(得分:1)
我认为你只想要一个相关的子查询:
update [B-table] as b
set rating = (select top 1 rating
from [A-table] as a
where a.pid = b.pid and
a.datechange <= b.matchdate
order by a.datechange desc
) ;
注意:由于MS Access处理top
的方式,子查询可以在出现平局时返回多行。对此的正常解决方案是在order by
中包含一个额外的键值,以防止绑定。但是,“a”表中似乎没有唯一的键。