0

有2张桌子TableA

    StudentID   MeetingID  TeacherID   Date
     001         1002581    1056      10-12-2012
     001         1006789    1056      10-13-2012
     001         1006754    1058      10-13-1012

再来一张B桌

     StudentID      MeetingID    TeacherID     Date        Value
         001          1002581      1056         10-12-201     15
         001          1002856      1056         10-20-2012    21

条件是表 A 中特定学生教师会议的 max(date) 与表 B 中同一学生教师会议的 max(date) 与值相匹配。我希望看到结果集类似于

   StudentID       MeetingID     TeacherID     Date          Value
   001             1006789       1056          10-20-2012     21

我怎样才能达到上述结果

4

2 回答 2

1

First, I'm curious why you have the same data in two separate tables instead of linking them via ID. I.e. Meetings -> Values

Per your requirements, this should work. This finds the most recent meeting which is present in both tables.

SELECT B.* 
FROM B INNER JOIN A ON B.StudentID = A.StudentID AND B.MeetingID = A.MeetingID AND B.Date = A.Date
WHERE B.Date = (SELECT MAX(Date) FROM A WHERE A.StudentID = B.StudentID AND A.MeetingID = B.MeetingID)

Here's the Fiddle: http://sqlfiddle.com/#!6/d15ca/4

于 2012-11-14T18:23:55.277 回答
1
SELECT TOP 1 c.StudentID,c.MeetingID,c.TeacherID,c.tab1_dates,c.VALUE
FROM 
(
    SELECT a.StudentID,a.MeetingID,a.TeacherID,a.Dates AS tab1_dates,b.Dates AS tab2_dates,b.VALUE,
    ROW_NUMBER() OVER (ORDER BY a.Dates,b.Dates) AS RN1
    FROM tab2 b
    INNER JOIN
    (
      SELECT StudentID,MeetingID,TeacherID,Dates FROM tab1
    ) a
    ON b.StudentID = a.StudentID
    AND b.TeacherID = a.TeacherID
        ) c
ORDER BY RN1 DESC

--SQL 小提琴 - http://www.sqlfiddle.com/#!3/c6cea/1

抱歉,格式不好。

于 2012-11-14T19:03:43.787 回答