有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的特定学生教师会议的最大(日期)与表B中相同学生教师会议的最大(日期)与该值相匹配。我希望看到结果集像
StudentID MeetingID TeacherID Date Value
001 1006789 1056 10-20-2012 21
我如何实现上述结果集
答案 0 :(得分:1)
首先,我很好奇为什么你在两个单独的表中拥有相同的数据,而不是通过ID链接它们。即会议 - >值
根据您的要求,这应该有效。这将找到两个表中的最新会议。
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)
答案 1 :(得分: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
抱歉,格式不正确。