How to get data from the previous row in SQL?

3

How to create a column with the value of the previous row in another column? Here's an example, I have the time column and I want to create the column time_lag :

Tabela inicial:  
id | title   | time  | domain  
32   title1    12:30   domain1  
33   title1    13:30   domain2  
34   title2    14:20   domain1  
35   title2    14:50   domain2  
36   title3    15:30   domain5  

Expected result:

id | title   | time  | domain |time_lag  
32   title1    12:30   domain1  
33   title1    13:30   domain2 12:30  
34   title2    14:20   domain1 13:30  
35   title2    14:50   domain2 14:20  
36   title3    15:30   domain5 14:50  
    
asked by anonymous 07.11.2016 / 13:20

2 answers

1

If your id is always auto increment, you simply do a sub-select and pass the id-1 of the external select.

declare @teste table
(
   id int,
   title varchar(10),
   time time, 
   domain varchar(10)
)


insert into @teste values

(32,   'title1'   ,'12:30'   ,'domain1'),  
(33 ,  'title1'    ,'13:30'   ,'domain2'),    
(34,   'title2'    ,'14:20'   ,'domain1'),    
(35,   'title2'    ,'14:50'   ,'domain2'),    
(36 ,  'title3'    ,'15:30'   ,'domain5')  


select * , (select time from @teste t1 where t1.id = t2.id - 1) as time_lag
from @teste t2

Or even;

select * , (select top 1 time from @teste t1 where t1.id < t2.id order by time desc ) as time_lag
from @teste t2

Change the top 1 by rownum = 1 if it is oracle or LIMIT 1 if it is mysql.

    
07.11.2016 / 14:38
2

You can create a new column to your table and at the time of inserting do something like:

INSERT INTO minhatabela (title, time, domain, time_lag) VALUES 
(
    'title1',
    '12:30', /*Não sei o tipo deste campo apesar do nome*/
    'domain1',
     SELECT time FROM minhatabela ORDER BY id DESC LIMIT 1
)

This would cause the value of time_lag to be the time value of the last record entered

    
07.11.2016 / 13:33