我有一个文件(不是我的设计!)来自具有多个字段的HR系统,并且不同的字段集具有不同的生效日期。我不知道这3个字段中哪一个日期更旧或更新。我简化了字段的数量,但原则是成立的:
rec# EmpNmbr Store StorEffDate Part PT Eff EmpGrp EmpGrp
Time Date Eff Date
1 90122 T202 03/07/2018 X 26/07/2018 Summary 01/07/2018
2 90122 LR86 13/08/2018 20/07/2018 Regular 14/08/2018
3 90122 T707 11/10/2018 X 03/09/2018 Summary 12/09/2018例如,我需要拆分记录1,这样就有3条记录:
生效日期和数据:
2018年1月7日至2018年2月7日,其中EmpGrp =摘要,Parttime和Store为空(我将从2018年1月7日的当前活动数据中获取实际数据)。
03/07/2018 to 25/07/2018 with Store = T202, EmpGrp = Summary, and Parttime null.
26/07/2018 to 01/01/3000 with Store = T202, EmpGrp = Summary, and Parttime=X然后从记录2开始,我需要:
20/07/2018 to 12/08/2018 T202 (from record above), Parttime=''and EmpGrp = Summary
13/08/2018 to 13/08/2018 LR86, Parttime=''and EmpGrp = Summary
14/08/2018 to 01/01/3000 LR86, Parttime=''and EmpGrp = Regular等
希望这是清楚的,但我需要能够做的是将每条记录分成3条,并按照3个有效日期字段中的一个按日期顺序对它们进行排序,并将各个数据字段与其日期有效字段相关联。
发布于 2018-08-25 11:40:50
nycoy,你应该解释一下你将一行“分割”成多行(2或3)的逻辑。在不了解逻辑的情况下,根据提供的示例和预期结果,我“猜测”这可能是您想要的。如果不是,它应该引导您更改您的实际逻辑
-- Sample Table
declare @sample table
(
rec# int,
EmpNmbr int,
Store varchar(5),
StorEffDate date,
PartTime char(1),
PTEffDate date,
EmpGrp varchar(10),
EmpGrpEffDate date
)
-- Sample Data
insert into @sample
select 1, 90122, 'T202', '2018-07-03', 'X', '2018-07-26', 'Summary', '2018-07-01' union all
select 2, 90122, 'LR86', '2018-08-13', null, '2018-07-20', 'Regular', '2018-08-14'
-- The Query
select rec#, n.EffDate, n.ExpDate, n.Store, n.EmpGrp, n.PartTime
from @sample s
cross apply
(
select EffDate = s.StorEffDate, ExpDate = dateadd(day, -1, s.PTEffDate), s.Store, s.EmpGrp, PartTime = null
where StorEffDate < PTEffDate
union all
select top 1 EffDate = s.PTEffDate, ExpDate = dateadd(day, -1, s.StorEffDate), x.Store, x.EmpGrp, PartTime = null
from @sample x
where s.PTEffDate < s.StorEffDate
and x.StorEffDate < s.StorEffDate
order by x.StorEffDate desc
union all
select top 1 EffDate = s.StorEffDate, ExpDate = s.StorEffDate, s.Store, x.EmpGrp, s.PartTime
from @sample x
where s.StorEffDate < s.EmpGrpEffDate
and x.StorEffDate < s.StorEffDate
order by x.StorEffDate desc
union all
select EffDate = s.PTEffDate, ExpDate = '01/01/3000', s.Store, s.EmpGrp, s.PartTime
where s.PTEffDate > s.EmpGrpEffDate
union all
select EffDate = s.EmpGrpEffDate, ExpDate = '01/01/3000', s.Store, s.EmpGrp, s.PartTime
where s.PTEffDate < s.EmpGrpEffDate
) n
order by rec#, EffDatehttps://stackoverflow.com/questions/52006058
复制相似问题