SQL Server combining 2 rows in 1 from one table

I have a table with JobID (PK), EmployeeID (FK), StartDate, EndDate, containing data such as:

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'

I want to return a record for each EndDate for the job, and then the same StartDate staff for its next coming work (by date). Therefore, from the above results, the result will be

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

Thank any help!

+3
source share
2 answers

Lance code has a problem. Here is the corrected request that will work:

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
+2
source

Something like this would be one way:

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

Good luck

0
source

Source: https://habr.com/ru/post/1747800/


All Articles