sql server - SQL linking by Rank() Over -


i have calculate days when container out of facility, each time container arrives has different primary key same id. same container can leave , arrive multiple times of course have count days between closest departure , arrival. i've been trying using rank() on function counting departures , arrivals:

select distinct *, datediff(day,c_out.time_out, c_in.time_in) days   (select container_id , time_out , rank() on (partition container_id, order time_out) leave_no containers departure_type='truck'              --edit2 ************************************ ) c_out inner join (select container_id incoming_id , time_in ,rank () on (partition container_id, order time_in) arrive_no containers) c_in on c_out.container_id=c_in.incoming_id  c_out.leave_no=c_in.arrive_no+1 

the idea here match leaves entries: if container left n-th time, next arrival n+1

but result receive like

container_id   time_out    leave_no  incoming_id  time_in    arrive_no  days abc123         2014-04-11     2      abc123       2013-11-21   1         -141 

edit: while presented below solution work, i'd still know how join on rank()

edit2: let me clarify: containers have leave in particular way (one of possible ones)

you try more brute-force, bit like:

select container_id , time_out , (select min(c2.time_in)        containers c2        c2.container_id = c1.container_id        , c2.time_in > c1.time_out) returned containers c1 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -