问题
Possible Duplicate:
SQL SERVER SELECTING ROW
If I have this table below
id time
start 08.00 AM
stop 09.00 AM
stop 09.30 AM
start 09.30 AM
start 11.00 AM
start 11.30 AM
stop 11.30 AM
stop 12.00 PM
I want output that looks like output below:
Any solution?
This is how the output I want:
id time end_time interval
start 08.00 AM 09.00 AM 60 minute
stop 09.00 AM 09.30 AM 30 minute
start 09.30 AM 11.30 AM 120 minute
stop 11.30 AM 12.00 PM 30 minute
stop 12.00 PM NULL NULL
回答1:
I want output that only take every first start and every start after stop and the latest stop
That's easily done with the row_number() window function:
; with numbered as
(
select row_number() over (order by [time]) rn
, count(*) over() as cnt
, *
from Table1
)
select *
from numbered cur
left join
numbered prev
on cur.rn = prev.rn + 1
left join
numbered next
on cur.rn = next.rn - 1
where cur.rn in (1, cur.cnt) -- first or last row
or (cur.id = 'start' and prev.id = 'stop') -- start after stop
order by
cur.rn
Live example on SQL Fiddle.
Not that your example output does not meet your requirements. It includes several rows that match neither of the three criteria (first row, last row, start after stop.)
来源:https://stackoverflow.com/questions/14582242/sql-selecting-row