Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
vss
Starting Member
1 Post |
Posted - 2011-05-13 : 18:53:09
|
I have several SQL record in a table that I need to pair two by two.For eg. I have the folwing data...ID TYPE DATE_TIME------------------------------1 IN 2011-01-01 09:001 OUT 2011-01-01 12:001 IN 2011-01-01 13:001 OUT 2011-01-01 17:002 IN 2011-01-01 09:002 OUT 2011-01-01 12:002 IN 2011-01-01 13:002 OUT 2011-01-01 17:00I need to output....ID DATE_TIME_IN DATE_TIPE_OUT------------------------------------------1 2011-01-01 09:00 2011-01-01 12:001 2011-01-01 13:00 2011-01-01 17:002 2011-01-01 09:00 2011-01-01 12:002 2011-01-01 13:00 2011-01-01 17:00Any Ideas how to do this with just SQL commands. |
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2011-05-13 : 19:05:18
|
[code];with cte as( select *,row_number() over(partition by id order by date_time) as rownum from YourTable)select a.id, a.date_time as date_time_in, b.date_time as date_time_outfrom cte a inner join cte b on a.id = b.id and a.rownum+1 = b.rownumwhere a.[type] = 'IN' and b.[type] = 'OUT'order by a.id, a.rownum[/code]This assumes that the data is always "clean" - i.e., each "IN" is paired with a corresponding "OUT" and that for a given ID, they are always alternating as IN,OUT,IN,OUT. |
 |
|
|
|
|