Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to link the pairs of values from 2 columns

I have a table [tt] with 2 columns which has a set of values that can repeat.
Columns are named [a] and [b]:

[a] [b]
1   2
1   3
1   4
2   1
2   3
3   2
4   1
4   5
5   4
5   6

I know how to query only the pairs:

SELECT t1.A, t1.B
    FROM tt AS t1
INNER JOIN tt AS t2
    ON t1.A = t2.B AND t1.B = t2.A

But how can I link the pairs together with adding a new column [pair_id] f.e. like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[a] [b] [pair_id]
1   2   1
2   1   1
1   4   2
4   1   2
2   3   3
3   2   3
4   5   4
5   4   4

Thank you!

>Solution :

Try the dense_rank function ordered by least and greatest functions.

select a, b,
  dense_rank() over (order by least(a, b), greatest(a, b)) pair_id
from tbl

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading