怎么跨表查询时间相隔最近的值,急等

酷de小刚 2015-05-23 05:12:16
数据库:ACCESS
一共有三个表:
Student表:ID, StudentName
-------------------------------------------------
1 张三
2 李四
3 王五


Test表: ID,StudentID, TestTime
------------------------------------------------------
1 1 2015/05/23
2 2 2015/04/23
3 3 2015/03/23

Other表: ID,StudentID,OtherTime
----------------------------------------------------
1 1 2015/06/23
2 1 2015/07/23
3 2 2015/08/23
4 2 2015/02/23


结果表: StudentName TestTime OtherTime
--------------------------------------------------------------------
张三 2015/05/23 2015/06/23
李四 2015/04/23 2015/02/23
王五 2015/03/23 空

请问如何写SQL语句,才能得到上述结果表:
1、Test和Other表中的StudentID是Student表中ID的外键;
2、结果表的StudentName,TestTime,OtherTime三个字段分别来自Student,Test,Other三个表,由Student表中ID字段关联,即 where Student.ID = Test.StudentID and Test.StudentID = Other.StudentID and Other.StudentID = Student.ID;
3、结果表中的每一行都对应Test表中的其中一行,且Test表中的每一行都要出现在结果表中;
4、结果表中OtherTime取OtherTime和TestTime时间差最小的一个值,如果没有找到对应的时间值,则为空;
请问为了得到结果表,怎么写SQL语句,主要是怎么取时间差最小的一个值?
想了一天都没想出来,求助,谢谢!
...全文
123 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
worldy 2015-05-24
  • 打赏
  • 举报
回复
4那个要求对access来说难度不小,还是将数据加载到客户端,由客户端分析处理
酷de小刚 2015-05-24
  • 打赏
  • 举报
回复
引用 1 楼 worldy 的回复:
select StudentName,TestTime,othertime from (select last(studentid) as studentId1,last(othertime) as othertime from other group by studendid as tblA) innerjoin student on tbla.studenid1=student.id inner join test on student.id =test.studentid
谢谢! 貌似您这个是选择最后一个时间,而不是“4、结果表中OtherTime取OtherTime和TestTime时间差最小的一个值,如果没有找到对应的时间值,则为空;”。 不知道我的理解对不对?
worldy 2015-05-23
  • 打赏
  • 举报
回复
select StudentName,TestTime,othertime from (select last(studentid) as studentId1,last(othertime) as othertime from other group by studendid as tblA) innerjoin student on tbla.studenid1=student.id inner join test on student.id =test.studentid

4,017

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧