I have a table which is created by joining 2 tables and now the two columns looks like having a many-to-many
relationship. I want to convert this to a one-to-one
relationship meaning, values in both the columns has to be unique
. Here is a sample setting;
create table Test(id1 integer, id2 integer);
insert into Test(id1, id2) values(1, 10);
insert into Test(id1, id2) values(1, 20);
insert into Test(id1, id2) values(2, 10);
insert into Test(id1, id2) values(2, 20);
select * from Test;
id1 | id2 |
---|---|
1 | 10 |
1 | 20 |
2 | 10 |
2 | 20 |
I want to convert the above table into something as below;
tbl1
id1 | id2 |
---|---|
1 | 10 |
2 | 20 |
OR
tbl2
id1 | id2 |
---|---|
1 | 20 |
2 | 10 |
How to write a SQL query to convert test
table to tbl1
or tbl2
?
This will take out unique values as mentioned in the comments on my other answer.
SELECT a.id1, b.id2
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY id1) AS RowNum FROM (SELECT DISTINCT id1 FROM test) x
) AS a,
(
SELECT *, ROW_NUMBER() OVER (ORDER BY id2) AS RowNum FROM (SELECT DISTINCT id2 FROM test) x
) AS b
WHERE a.RowNum = b.RowNum
Let me know if there is something I misunderstood.