0

I'm struggling to find a way to get consecutive pairs in a column of a table but failed so far. To explain more specifically, let me give an example.

Let's say I have a table (t1) with 1 column (col1) of char as follows:

col1
------
a
a
a
c
e
a
g
i

What I want to get is consecutive pairs like (a,a) (a,a) (a,c) (c,e) (e,a) (a g) (g,i). For example, building a new table(t2) which has a column(col2) of string as follows:

col2
------
a,a
a,a
a,c
c,e
e,a
a,g
g,i

(if I can exclude the pairs of same value (e.g. (a,a)), it would be better)

Please assume that there is no analytic function like lag() and unable to use pl/sql. I have to solve this problem with basic sql statements.

I have a quite simple sql query to solve this kind of problem as follow:

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

But this query is working when we assume there is no duplication.

Please help. Any comment or idea would be very thankful.

4

1 回答 1

1

You can use a ROW_NUMBER to achieve this:

SELECT a.col,b.col
FROM    (SELECT col,ROW_NUMBER () OVER (ORDER BY (SELECT 1)) 'Row_Rank'
         FROM Table1
         )a
LEFT JOIN    (SELECT col,ROW_NUMBER () OVER (ORDER BY (SELECT 1)) 'Row_Rank'
         FROM Table1
        )b
ON a.Row_Rank = b.Row_Rank - 1

Ideally you'd have something that you could segment this by, as it's nice to ensure ordering, but the above works. The ROW_NUMBER just creates a number for each row, which you can use to self-join with an offset of 1 row.

EDIT: Changed to LEFT JOIN, depending on what you want to return for the last record you can use LEFT or INNER, and you could wrap the selected columns in ISNULL if you wanted to return a specific value to be paired with the last value that has no next row.

于 2013-06-14T13:22:55.223 回答