2

我想将两条记录(来自同一个表)加入一行,多列。

工作经历结构如下:

StaffID     StartDate       EndDate         DeptID
==================================================
1           2010-10-01      2011-01-19      1
1           2011-01-20      2012-12-31      2
1           2013-01-01      2013-05-29      4

如果相同的 StaffID 和第二条记录的开始日期是第一条记录的结束日期后 1 天,我如何将两行合并为一行(连续就业)

输出应该是这样的

StaffID     EffectiveDate   New_DeptID      Prev_DeptID     
==================================================
1           2011-01-20      2               1
1           2013-01-01      4               2

以下是我的 sql 语句,但它不起作用

  select distinct
    ca1.StaffID,
    ca1.ProjectDepartment as Prev_DeptID, ca1.StartDate, ca1.EndDate, 
    ca2.ProjectDepartment as New_DeptID, ca2.StartDate, ca2.EndDate
from 
emp_hist as ca1,
emp_hist as ca2
where 
    (ca1.StaffID = ca2.StaffID) 
    and ca1.StartDate<>ca2.StartDate
    and ca1.EndDate <>ca2.EndDate
    and  ca2.startdate= DATEADD(day, 1, ca1.enddate)

例如表中有两条记录(真实数据):

StaffID     StartDate                   EndDate                     DeptID
===========================================================================
1           2010-04-12 12:00:00.000     2013-02-28 00:00:00.000     1
1           2013-03-01 12:00:00.000     2013-08-29 11:02:59.877     2

我无法使用我的 sql 语句检索此记录

4

2 回答 2

1

您的问题是日期有时间部分。您似乎正在使用 SQL Server。您可以通过执行以下操作来修复您的查询:

select ca1.StaffID,
       ca1.ProjectDepartment as Prev_DeptID, ca1.StartDate, ca1.EndDate, 
       ca2.ProjectDepartment as New_DeptID, ca2.StartDate, ca2.EndDate
from emp_hist as ca1 join
     emp_hist as ca2
     on ca1.StaffID = ca2.StaffID and
        cast(ca1.StartDate as date) <> cast(ca2.StartDate as date) and
        cast(ca1.EndDate as date) <> cast(ca2.EndDate as date) and
        cast(ca2.startdate as date) = DATEADD(day, 1, cast(ca1.enddate as date));

我还用改进的连接语法替换了隐式连接。

于 2013-08-29T03:10:37.793 回答
1

如果您使用的是 SQL 2012,请尝试使用滞后函数。

select distinct
  ca1.StaffID,
  ca1.EndDate,
  ca1.ProjectDepartment as New_DeptID, 
  LAG(ca1.ProjectDepartment) OVER (PARTITION BY ca1.StaffId ORDER BY ca1.EndDate) as Prev_DeptID
from 
  emp_hist as ca1 

如果不是,请使用 RANK 函数和子查询

select 
  eh.StaffID,
  eh.EndDate,
  eh.ProjectDepartment as New_DeptID, 
  eh1.ProjectDepartment as Prev_DeptID
from 
(select *, RANK(EndDate) OVER (PARTITION BY StaffId ORDER BY EndDate) as Rank 
from emp_hist) eh left join (
  select distinct
    StaffID,
    EndDate,
    ProjectDepartment, 
    RANK(EndDate) OVER (PARTITION BY StaffId ORDER BY EndDate) as Rank
from 
  emp_hist) eh1 on eh1.staffid=a.staffid and eh1.rank=eh.rank-1
于 2013-08-29T03:53:02.430 回答