加入CTE表SQL服务器

时间:2019-02-13 13:03:00

标签: sql sql-server

您好,我有下面的CTE表,我正在使用表上每个员工的上班日期和时间加入各种员工数据。我需要将此表TACLO联接到CTE上,以便查询返回与CTE表上的日期匹配的数据,但是当我尝试内部左或右联接时,仅出现在匹配的日期有时钟的记录,但是我需要看到

有什么想法吗?

非常感谢

DECLARE @Start DATE = '2018-1-1', @End DATE = GETDATE()
;WITH 
dates AS
(   SELECT thedate = @Start
    UNION ALL
    SELECT dateadd(day,1,dates.thedate)
    FROM dates
    WHERE dateadd(day,1,dates.thedate) <= @End)

select distinct cast(a.DET_NUMBER as varchar) as 'Frontier ID',
e.CDN_CARD_ID, 
CONCAT (a.DET_G1_NAME1,' ',a.DET_SURNAME) as 'Name',
c.POS_TITLE as 'Position',
c.POS_L3_CD as 'Department', 
c.POS_L4_CD as 'Department 2', 
cast(a.DET_DATE_JND as date) as 'Start Date', 
cast(b.TER_DATE as date) as 'Leaving Date', 
CONCAT (d.DET_G1_NAME1,' ',d.DET_SURNAME) as 'Team Manager', 
f.CLO_DATE2,
min(f.CLO_TIME2) over (partition by f.CLO_DATE2,e.CDN_CARD_ID) as earliest_time,
max(f.CLO_TIME2) over (partition by f.CLO_DATE2,e.CDN_CARD_ID) as latiest_time, q.thedate

from EMDET a
left outer join EMTER b on a.DET_NUMBER = b.DET_NUMBER
left outer join EMPOS c on a.DET_NUMBER = c.DET_NUMBER
left outer join EMDET d on c.POS_MANEMPNO = d.DET_NUMBER
left outer join TACDN e on a.DET_NUMBER = e.DET_NUMBER
left outer join TACLO f on e.CDN_CARD_ID = f.CLO_CARD_NO
left outer join dates q on f.CLO_DATE2 = q.thedate

Where (b.TER_DATE is null or c.POS_END>=GETDATE()) and 
c.POS_TITLE is not null and 
(c.POS_END<=Cast('1992-01-01' as datetime) or c.POS_END>=GETDATE()) and q.thedate = '2019-02-13'

order by [Team Manager] asc, e.CDN_CARD_ID asc, f.CLO_DATE2 asc

OPTION (maxrecursion 0)

0 个答案:

没有答案