【问题标题】:Need SQL to merge to data points into one effective dated table需要 SQL 将两个数据点合并到一个有效的日期表中
【发布时间】:2020-11-14 17:22:38
【问题描述】:

我有如下文件中的入站数据。它有EmployeeID、ManagerStartDate、ManagerID、JobStartDate、JobID 列。此文件总是包含最新的行。

以下是示例行:

EmployeeID,ManagerStartDate,ManagerID,JobStartDate,JobID
1001,11/1/2020,M1001,10/1/2020,J01
1002,08/1/2020,M1001,11/13/2020,J02
1003,null,null,9/1/2020,J01

我需要每天读取这些数据并将结果存储到一个有效的日期表中,该表的列为EmployeeID、ManagerID、JobID、StartDate、EndDate。

我的预期输出:

EmployeeID | ManagerID | JobID | StartDate  | EndDate
-----------+-----------+-------+------------+------------
1001       | null      | J01   | 10/01/2020 | 10/31/2020
1001       | M1001     | J01   | 11/01/2020 | 12/31/9998
1002       | M1001     | null  | 08/01/2020 | 11/12/2020
1002       | M1001     | J02   | 11/13/2020 | 12/31/9998
1003       | null      | J01   | 09/01/2020 | 12/31/9998

当第二天文件中的ManagerID 和JobID 发生任何变化时,反映了最新数据,我需要与表中的数据进行比较,并根据需要进行更新。

我尝试了不同的 SQL 集,但我被卡住了,我无法缩小所有不同的场景。有人可以帮助我指导解决方案以获得预期的输出吗?

谢谢, 纳文

【问题讨论】:

    标签: sql sql-server date-range


    【解决方案1】:

    我认为您希望从员工/日期组合列表开始,然后使用 apply 引入最近的经理和工作:

    with ed as (
          select employeeid, managerstartdate as startdate
          from t
          union. -- on purpose to remove duplicates
          select employeeid, jobstartdate as startdate
          from t
         )
    select ed.*, m.managerid, j.jobid,
           dateadd(day, -1,
                   lead(startdate, 1, '9999-01-01') over (partition by employeeid order by startdate)
                  ) as enddate
    from ed outer apply
         (select top (1) t2.managerid
          from t t2
          where t2.employeeid = ed.employeeid and
                t2.managerstartdate <= ed.startdate
          order by t2.managerstartdate desc
         ) m outer apply
         (select top (1) t2.jobid
          from t t2
          where t2.employeeid = ed.employeeid and
                t2.jobstartdate <= ed.startdate
          order by t2.jobstartdate desc
         ) j;
    

    【讨论】:

    • 谢谢 Gordon,我们如何获得所需的 EndDates?
    • @Naveen。 . .您可以使用lead()。
    • 太棒了,这清楚地表明我在 SQL 方面的知识有限,而你真的很擅长。我对如何使用第二天的数据维护此表进行了跟进。这是一个示例,对于员工 1001,它在第二天的文件中已更改为如下所示。 EmployeeID,ManagerStartDate,ManagerID,JobStartDate,JobID 1001,12/1/2020,M1002,10/1/2020,J01 相同的 SQL 如何更新现有记录以维护经理值,因为它是 M1001 直到 11/30/ 2020 年,从 2020 年 12 月 1 日开始,经理为 M1002,其中 JobID 没有更改。
    猜你喜欢
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2020-08-24
    • 2015-10-29
    • 1970-01-01
    • 2018-06-23
    相关资源
    最近更新 更多