sql server access ONLY the previous record based on a selection -


given following table

id  short_name  long_name   category    departure   rec_order 1548    aaa aaa aa  station 10:00   1 1548    bbb bbb bb  station 11:10   2 1548    ccc ccc cc  station 12:30   3 1548    ddd ddd dd  border  15:30   4 

i want access last row (station) before border. return

ccc ccc cc  station 12:30   3 

because database rather big , timetable in real life complicated structure , have in indexed view putting data (here simplification sake of example) i'm looking higher performance solution (possibly no cross join).

i've tried selection lag and/or lead, offset fetch solutions not working put in clause where category = 'border' selects border row.

this query working, i'm looking more optimised solution:

select top 1 m1.short_name  m1.long_name v_timetable m1 ( noexpand ) join  ( select top 1 rec_order, id v_timetable v ( noexpand )    v.id = 1548 , category = 'border' order rec_order desc ) m2 on m1.id = m2.id m1.rec_order < m2.rec_order order m1.rec_order desc 

i want point out alternative solution:

select t.* (select t.*,              lead(category) on (partition id order departure) next_category       t      ) t next_category = 'border'; 

important note: not return ids have no border in them. return multiple rows ids have border multiple times. these seem more in line question asked selecting 1 row -- , consistent sample code provided in question.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -