主查细节的SQL查询

时间:2008-12-09 11:50:12

标签: sql

主表包含ID和PersonName 课程表包含ID,CourseName 详细信息表包含ID,MasterID,CourseID,StartDate,EndDate

我想创建显示人员名单(PersonName)的报告以及他们采取的唯一最后一个课程(因此每个人只列出一次):

PersonName - CourseName - StartDate - EndDate

2 个答案:

答案 0 :(得分:2)

select m.PersonName, c.CourseName
from   Master m
join   Detail d on d.MasterID = m.ID
join   Course c on c.ID = d.CourseID
where  d.StartDate = (select max(d2.StartDate)
                      from   Detail d2
                      where  d2.MasterID = m.ID
                     )

答案 1 :(得分:0)

    Select personname,coursename from details 
    inner join course on course.id = details.courseid 
    inner join master on master.id = details.masterid
    inner join (select max(startdate) ,  courseid,masterid 
    from details group by masterid,courseid ) as tb1
    on tb1.courseid = details.courseid and tb1.masterid = details.masterid