簡體   English   中英

在ms-access中使用sql從另一個表中使用最大日期和值更新表

[英]updating a table using the max date and values from another table using sql in ms-access

我有以下情況:我想使用tableA的評級來更新tableB 面臨的挑戰是:評分會隨機變化,並且在更新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

SQLFiddle與數據庫架構

總結:我希望與比賽日期或比賽日期之前的最大日期更改相對應的評級。

我認為您只需要一個相關的子查詢:

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”表中似乎沒有唯一鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM