Select picking up previous line

0

What do I have to use in SQL SERVER 2008 to pick up the line before a certain closing. For example if in my where below if the alert is = 99 I want to know the alert and the speed before the alert.

Speed     Data                  Alerta
58   '2017-09-13 10:08:04.290'  44
20   '2017-09-13 10:08:51.340'  99
56   '2017-09-13 10:09:21.450'  204
40   '2017-09-13 10:09:27.470'  99
34   '2017-09-13 10:09:37.570'  204

In this example there were two alert 99 where it was at a speed of 20 and 40 km, I want to return this line before the alert with the highest speed:

Speed     Data                  Alerta
56   '2017-09-13 10:09:21.450'  204 
    
asked by anonymous 30.10.2017 / 13:22

2 answers

2

A little big, but solves your problem ..

declare @Velocidades table
(
    Speed int,
    Data Datetime,
    Alerta int
);


insert into @Velocidades  values
(58,'2017-09-13 10:08:04.290',44),
(20,'2017-09-13 10:08:51.340',99),
(56,'2017-09-13 10:09:21.450',204),
(40,'2017-09-13 10:09:27.470',99),
(34,'2017-09-13 10:09:37.570',204)

declare @VelocidadesTeste table
(
    Speed int,
    Data Datetime,
    Alerta int
);


DECLARE @Speed int, @Data Datetime, @Alerta int;  

DECLARE db_cursor CURSOR FOR  
    SELECT Speed, Data, Alerta
    FROM @Velocidades
    WHERE Alerta = 99; 

OPEN db_cursor   
FETCH NEXT FROM db_cursor INTO @Speed, @Data, @Alerta   

WHILE @@FETCH_STATUS = 0   
BEGIN   
       insert into @VelocidadesTeste
       select top 1 * from @Velocidades 
       where Data < @Data 
       order by Data desc;

       FETCH NEXT FROM db_cursor INTO @Speed, @Data, @Alerta   
END   

CLOSE db_cursor   
DEALLOCATE db_cursor


select * from @VelocidadesTeste
where Speed = (select max(Speed) from @VelocidadesTeste)
    
30.10.2017 / 14:18
-1

Here is a suggestion for the 2008 version of SQL Server:

-- código #1
with 
Alerta99 as (
SELECT Data, 
       Seq= row_number() over (order by Speed desc)
  from tbAlerta
  where alerta = 99
),
MaiorVelocidade99 as (
SELECT Data
  from Alerta99
  where Seq = 1
)
SELECT top (1) Speed, Data, Alerta
  from tbAlerta as A
  where A.Data < (SELECT Data from MaiorVelocidade99)
  order by A.Data desc;

The CTE Alerta99 separates all lines whose alert is 99 and creates a column with a sequence of them, starting with the one with the highest speed and incrementing as the speed decreases.

The CTE MajorValue99 gets the date of the highest speed line for alert 99.

At the end, the line immediately preceding the highest speed line for alert 99 is returned, using the date as the criterion.

Not tested; may contain errors.

    
30.10.2017 / 15:22