简体   繁体   中英

Merge rows SQL Server 2014

Let's say I have 3 rows in my table with the following data stored in them.

ROW 1: 10:00 | 10:15 | Washington
ROW 2: 10:00 | 10:01 | New York
ROW 3: 10:02 | 10:03 | New York
ROW 4: 10:05 | 10:08 | New York
ROW 5: 10:20 | 10:40 | New York

The '|' is a column seperator.

How can I find this data in my table and merge ROW 2 and ROW 4 together. The outcome should be something like this:

ROW 1: 10:00 | 10:08 | New York

I want to ignore the first and last row, since there the time span for merging is overridden and I only want "New York" as city.

Something like: IF next is < 5 min ago THEN ROW 1.End_Time = ROW X.End_Time

Thank you in advance

It looks like you want the first (earliest start time) for a given location along with the end time of the next row for that location that has a start time of 5 minutes or more than the first. One method:

SELECT TOP(1)
      a.StartTime
    , b.EndTime
    , a.Location
FROM dbo.Table1 AS a
CROSS APPLY(
    SELECT TOP(1) EndTime
    FROM dbo.Table1 AS b
    WHERE
        b.Location = a.Location 
        AND b.StartTime >= DATEADD(minute, 5, a.StartTime)
    ) AS b
WHERE
    a.Location = 'New York'
ORDER BY
    a.StartTime;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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