Groups | Blog | Home
all groups > sql server misc > april 2004 >

sql server misc : Finding and inserting consecutive pairs


myname
4/5/2004 11:12:42 AM
Hello,

I'm trying to insert into a table consecutive pairs from another table.

Right now, I'm using a cursor but I wonder if there's a faster way.

Example:

My table1 contains a column of integers: 1, 20, 3, 45, 12

I want to obtain this in a two columns table Table2 :
(1;3) (3;12) (12;20) (20;45)

As I said, I use a cursor. I first sort Table1, and then go through it,
inserting every line with the one of previous fetch.

Is this possible with a double select on Table1, the second one
skipping the first line ?

Thank you very much for any help.


Branko Radovanovic
4/5/2004 4:32:17 PM

[quoted text, click to view]


select t1.col as col1, min(t2.col) as col2
from table1 t1 inner join table1 t2 on t2.col > t1.col
group by t1.col
order by t1.col


Works fine provided there are no duplicate values in table1. It is also
surprisingly quick...


--
Branko Radovanovic

Branko Radovanovic
4/5/2004 4:50:45 PM
[quoted text, click to view]

....as long as your row count is reasonably low, I must add...


--
Branko Radovanovic

Branko Radovanovic
4/5/2004 5:07:48 PM
[quoted text, click to view]

This is in fact *much* faster:

create table #temp (id int identity, col int)

insert into #temp
select col
from table1
order by col

select t1.col, t2.col
from #temp t1 inner join #temp t2 on t2.id = t1.id + 1
order by t1.col


The identity column trick...

--
Branko Radovanovic

myname
4/6/2004 8:25:16 AM

"Branko Radovanovic" <branko.radovanovic@ve-mil.REMOVE.hr> a écrit dans le
message news: lb98k1-sg42.ln1@news.ve-mil.hr...
[quoted text, click to view]

Thank you very much for your help.

But... isn't it the method I suggested in my last post of yesterday ?

Except that I included the subset thing...




Branko Radovanovic
4/6/2004 9:24:59 AM
[quoted text, click to view]

Yes it is, inasmuch as it involves the identity column - sorry about that...
Your post came to my server late, so I haven't read it before posting my own
solution...

--
Branko Radovanovic

AddThis Social Bookmark Button