这是continuation from my earlier question。
计划使用多个join语句创建视图。我已经准备好组装每个单独的组件:
select A.[Course Code], A.[Course Title],A.Result, A.[Employee No], A.[Employee Name], A.Section,
max(B.ActStartDate) as [Last Training Date], B.ValidTo as [Validity Period], A.[Status], A.Flag as [Record Flag]
from
(select c.CourseID, c.[CourseCode] as [Course Code], c.[CourseTitle] as [Course Title],
c.[CourseCode] + ' - ' + c.[CourseTitle] as [Result],
b.[EMPLOYEE_NO] as [Employee No], b.[EMPLOYEE_NAME] as [Employee Name],
b.[SECTION_CODE] + ' - ' + b.[SECTION_DESCRIPTION] as [Section], b.[EMPLOYEE_STATUS] as [Status], a.Flag
from [SQLDB3].[dbo].[ZOJT_EMP_COURSE] a inner join
[SQLDB3].[dbo].[vEMPLOYEE_PROFILE] b on a.Employee_No = b.EMPLOYEE_NO inner join
[SQLDB3].[dbo].[tTMS_Course] c on c.CourseCode = a.CourseCode) as A
inner join
(select a.SchID as [SchID], b.CourseID as [CourseID], a.EmpNo as [EmpNo],
b.ActStartDate as [ActStartDate], a.ValidTo as [ValidTo]
from [SQLDB3].[dbo].[tTMS_Training_Record] a
inner join
(select z.schid, z.CourseID as [CourseID],max(z.ActStartDate) as [ActStartDate]
from [SQLDB3].[dbo].[tTMS_Training_Schedule] z group by z.SchID, z.CourseID)as b
on a.SchID = b.SchID )as B on A.[Employee No]= B.EmpNo
group by A.CourseID, A.[Course Code], A.[Course Title],A.Result, A.[Employee No], A.[Employee Name], A.Section,
B.ValidTo, A.[Status], A.Flag
每个课程代码和员工组合中表中的最后一行培训日期的最大值不得为1行。
尽管这些组件可以单独很好地工作,但是当组合在一起时,我会得到多个具有相同课程代码和员工编号的记录,且具有不同的上次培训日期。
老实说,我在这里。有帮助吗?
答案 0 :(得分:1)
使用row_number窗口功能
with cte as
( select A.[Course Code],
A.[Course Title],
A.Result,
A.[Employee No],
A.[Employee Name], A.Section,
B.ActStartDate as [Last Training Date],
B.ValidTo as [Validity Period],
A.[Status], A.Flag as [Record Flag]
,row_number() over(partition by A.[Course Code], A.[Employee No] order by B.ActStartDate desc) rn
from
(select c.CourseID, c.[CourseCode] as [Course Code], c.[CourseTitle] as [Course Title],
c.[CourseCode] + ' - ' + c.[CourseTitle] as [Result],
b.[EMPLOYEE_NO] as [Employee No], b.[EMPLOYEE_NAME] as [Employee Name],
b.[SECTION_CODE] + ' - ' + b.[SECTION_DESCRIPTION] as [Section], b.[EMPLOYEE_STATUS] as [Status], a.Flag
from [SQLDB3].[dbo].[ZOJT_EMP_COURSE] a inner join
[SQLDB3].[dbo].[vEMPLOYEE_PROFILE] b on a.Employee_No = b.EMPLOYEE_NO inner join
[SQLDB3].[dbo].[tTMS_Course] c on c.CourseCode = a.CourseCode) as A
inner join
(select a.SchID as [SchID], b.CourseID as [CourseID], a.EmpNo as [EmpNo],
b.ActStartDate as [ActStartDate], a.ValidTo as [ValidTo]
from [SQLDB3].[dbo].[tTMS_Training_Record] a
inner join
(select z.schid, z.CourseID as [CourseID],max(z.ActStartDate) as [ActStartDate]
from [SQLDB3].[dbo].[tTMS_Training_Schedule] z group by z.SchID, z.CourseID)as b
on a.SchID = b.SchID )as B on A.[Employee No]= B.EmpNo
) select * from cte where rn=1