我有这个任务:
对于此任务,请在提供的数据集中使用以下表:
[Employee]
(包含所有员工的每个职位的名称和开始日期,业务密钥唯一标识每个员工)
[Position]
(包含每个职位的级别名称)
创建一个返回以下列的SQL语句
[EmployeeKey]
[EmployeeBK]
[Name]
[Level]
[ValidFrom]
[ValidTo]
列[ValidTo]必须符合以下规则: 1)该值必须是下一个位置开始日期前一天(没有重叠,位置历史记录中没有“漏洞”) 2)最后一个位置应被视为未结,并被赋予默认结束日期
'2222-12-31' (YYYY-MM-DD)
奖金问题:确定数据集中的数据质量问题
[dbo].[Employee](
[EmployeeKey] [int] NOT NULL,
[EmployeeBK] [int] NOT NULL,
[Name] [nvarchar](50) NOT NULL,
[ValidFrom] [date] NULL
)
[dbo].[Position](
[EmployeeKey] [int] NOT NULL,
[Level] [varchar](9) NULL
)
一些记录:
1. EmployeeKey EmployeeBK Name Level ValidFrom
15 2 Kayla Level 1 2013-01-01
54 2 Kayla Level 2 2013-03-15
63 2 Kayla Level 3 2013-04-19
81 2 Kayla Level 4 2013-07-28
116 2 Kayla Level 5 2014-05-31
143 2 Kayla Level 6 2015-01-15
171 2 Kayla Level 7 2016-03-25
193 2 Kayla Level 8 2016-05-31
194 2 Kayla Level 9 2016-05-31
11 3 Hudson Level 1 2013-01-01
38 3 Hudson Level 2 2013-01-30
49 3 Hudson Level 3 2013-02-20
80 3 Hudson Level 4 2013-07-26
91 3 Hudson Level 5 2013-11-05
101 3 Hudson Level 6 2013-12-28
105 3 Hudson Level 7 2014-03-24
提前谢谢!
答案 0 :(得分:0)
with ValidDate as
(select e.EmployeeKey, LEAD(e.ValidFrom, 1, '2222-12-31') over (partition by e.EmployeeBK order by p.[Level]) as ValidTo from
dbo.Employee e
left join dbo.Position p on p.EmployeeKey = e.EmployeeKey)
select distinct e.EmployeeKey
, e.EmployeeBK
, e.Name
, p.[Level]
, e.ValidFrom
, dateadd(day, -1, v.ValidTo) as ValidTo
--, v.ValidTo as ValidTest
from dbo.Employee e
join dbo.Position p on p.EmployeeKey = e.EmployeeKey
join ValidDate v on v.EmployeeKey = e.EmployeeKey
group by e.EmployeeKey, e.EmployeeBK, e.Name, p.[Level], e.ValidFrom, v.ValidTo
order by e.EmployeeBK