在sql -ms访问

时间:2015-06-05 19:19:51

标签: sql ms-access

所以我很想知道。我从其他开发者那里得到了一个有趣的建议。所以我基本上有两个表,我加入一个查询,我希望查询中的结果表有一个额外的列来自联合表。

示例:

#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 |
 1   |  2   | 10-May-2014  |  No |
 2   |  1   | 15-May-2015  | Yes |
 3   |  3   | 10-Apr-2014  |  No |
 4   |  1   | 21-Apr-2015  | Yes |
 5   |  1   | 3-June-2015  | Yes |
 6   |  2   | 5-May-2015   |  No |

#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  |    4   |
 5   |  1   | 3-June-2015  |    20  |
 6   |  2   | 5-May-2015   |    3   |

这是我在下面尝试过的:

Select MsID, PID, MatchDate, A-table.rating as Rating from B-table
       left Join A-table 
          on B-table.PID = A-table.PID
             where B-table.MatchDate > A-table.Datechange;

任何帮助表示赞赏。解决方案可以在Vba中,只要它返回类似于我可以使用其他查询或报告操作的视图/表格。

1 个答案:

答案 0 :(得分:0)

根据数据集来考虑这一点......您需要一个列出每个玩家和匹配日期的MAX dateChange的集合。

...洙

SELECT MAX(A.DateChange) MDC, A.PID, B.Matchdate
FROM B-table B
INNER Join A-table A
 on B.PID = A.PID
and A.DateChange <= B.MatchDate
GROUP BY A.PID, B.Matchdate

现在我们接受它并将其加入到你已经完成的工作中,将表A和B中的结果限制为只有那些日期播放器和matchDate(我的内联表C)

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

我没有使用您的数据为此创建示例,因此未经测试,但我相信逻辑是合理的......

现在经过测试! SQL Fiddle虽然使用SQL服务器......

我的结果与您的结果完全不符。我认为对于定义规则的MSID 4,你预期的结果是错误的。