繁体   English   中英

SQL Server将同一个表中的2行合并为1

[英]SQL Server combining 2 rows into 1 from the same table

我有一个包含JobID(PK),EmployeeID(FK),StartDate,EndDate的表,其中包含以下数据:

1, 10, '01-Jan-2010 08:00:00', '01-Jan-2010 08:30:00'
2, 10, '01-Jan-2010 08:50:00', '01-Jan-2010 09:05:00'
3, 10, '02-Feb-2010 10:00:00', '02-Feb-2010 10:30:00'

我想为一个Job返回每个EndDate的记录,然后为同一个员工StartDate返回他的下一个直接工作(按日期时间)。 所以从上面的数据结果来看

Result 1: 10, 01-Jan-2010 08:30:00, 01-Jan-2010 08:50:00
Result 2: 10, 01-Jan-2010 09:05:00, 02-Feb-2010 10:00:00

非常感谢任何帮助!

Lance的代码有问题。 以下是可以使用的更正查询:

select j1.JobID, j1.EmployeeID, j1.EndDate, 
(
    select top 1 j2.StartDate 
      from Job j2
     where j2.EmployeeID = j1.EmployeeID
       and j2.StartDate > j1.EndDate
     order by j2.StartDate
) as NextStartDate
from Job j1

这样的事情会是一种方式:

select j1.JobID, j1.EmployeeID, j1.EndDate, 
(
    select top 1 j2.StartDate from Job j2
    where j2.EmployeeID = j1.EmployeeID
    order by j2.StartDate
    where j2.StartDate > j1.EndDate
) as NextStartDate
from Job j1

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM