I have a table with the following sample data:
Tag Loc Time1
A 10 6/2/15 8:00 AM
A 10 6/2/15 7:50 AM
A 10 6/2/15 7:30 AM
A 20 6/2/15 7:20 AM
A 20 6/2/15 7:15 AM
B 10 6/2/15 7:12 AM
B 10 6/2/15 7:11 AM
A 10 6/2/15 7:10 AM
A 10 6/2/15 7:00 AM
I need SQL to select the first (earliest) row in a sequence until location changes, then select the earliest row again until location changes. In other words I need the following output from above:
Tag Loc Time1
A 10 6/2/15 7:30 AM
A 20 6/2/15 7:15 AM
A 10 6/2/15 7:00 AM
B 10 6/2/15 7:11 AM
I tried this from Giorgos - but some lines from the select were duplicated:
declare @temptbl table (rowid int primary key identity, tag nvarchar(1), loc int, time1 datetime)
declare @tag as nvarchar(1), @loc as int, @time1 as datetime
insert into @temptbl (tag, loc, time1) values (1,20,'6/5/2015 7:15 AM')
insert into @temptbl (tag, loc, time1) values (1,20,'6/5/2015 7:20 AM')
insert into @temptbl (tag, loc, time1) values (1,20,'6/5/2015 7:25 AM')
insert into @temptbl (tag, loc, time1) values (4,20,'6/5/2015 7:20 AM')
insert into @temptbl (tag, loc, time1) values (4,20,'6/5/2015 7:25 AM')
insert into @temptbl (tag, loc, time1) values (4,20,'6/5/2015 7:30 AM')
insert into @temptbl (tag, loc, time1) values (4,20,'6/5/2015 7:35 AM')
insert into @temptbl (tag, loc, time1) values (4,20,'6/5/2015 7:40 AM')
select * from @temptbl
SELECT Tag, Loc, MIN(Time1) as time2
FROM (
SELECT Tag, Loc, Time1,
ROW_NUMBER() OVER (ORDER BY Time1) -
ROW_NUMBER() OVER (PARTITION BY Tag, Loc
ORDER BY Time1) AS grp
FROM @temptbl ) t
GROUP BY Tag, Loc, grp
Here is the results (there should only be one line for each tag)
Tag Loc time2
1 20 2015-06-05 07:15:00.000
1 20 2015-06-05 07:25:00.000
4 20 2015-06-05 07:20:00.000
4 20 2015-06-05 07:30:00.000
Assuming you're using MS SQL Server 2012 or newer, the lag window function will allow you to compare a row to the previous one:
SELECT tag, loc, time1
FROM (SELECT tag, loc, time1,
LAG (loc) OVER (PARTITION BY tag ORDER BY time1) AS lagloc
FROM my_table) t
WHERE loc != lagloc OR lagloc IS NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With