动态表创建SQLSever

时间:2019-02-13 10:01:24

标签: sql-server

我在SQL中有几个表,可用于保存员工数据,包括ID和时间。我需要创建一个报告以显示每个员工每天的时钟时间。我已经用下面的代码做到了。但是,由于仅在有条目的情况下才记录时钟,因此我需要显示工作日,其中没有员工的时钟记录。我曾考虑过要制作一个2019/2020年工作日表,其中包括每位员工每天的数据,并使用此表进行合并,但是当有人开始工作时,该表将需要不断更新。

表格有什么办法可以更新员工编号并复制工作日?

任何帮助将不胜感激

谢谢

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(CLO_TIME2) over (partition by f.CLO_DATE2, e.CDN_CARD_ID) as earliest_time,
    max(CLO_TIME2) over (partition by f.CLO_DATE2, e.CDN_CARD_ID) as latiest_time
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
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 f.CLO_DATE >='2019-01-01'
order by [Team Manager] asc,
         e.CDN_CARD_ID asc,
         f.CLO_DATE2 asc

1 个答案:

答案 0 :(得分:0)

您可以使用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 * 
FROM dates c
OPTION (maxrecursion 0);

然后过滤以排除非工作日(周末:直接从您的查询表,假期,假期,许可等从其他表中获取)

直接加入您的实际查询