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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query help

Author  Topic 

mavershang
Posting Yak Master

111 Posts

Posted - 2011-09-13 : 18:06:26
Hi there. I have a table like
Col1 Col2
1 100
2 121
3 130
...
100 1
...
121 2
...

Now what I want is: if there are two rows with Col1 and Col2 exchanged, then just save one of them.
For above table, I just want
1 100
2 121
3 130

Thanks in advance.

singularity
Posting Yak Master

153 Posts

Posted - 2011-09-13 : 19:58:34
[code]
select col1, col2
from yourtable
union
select col2, col1
from yourtable
[/code]
Go to Top of Page

mavershang
Posting Yak Master

111 Posts

Posted - 2011-09-14 : 11:18:11
Thanks for replying. But your query won't work since it actually selects all rows.

quote:
Originally posted by singularity


select col1, col2
from yourtable
union
select col2, col1
from yourtable


Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-09-14 : 11:53:05
so you're trying to insert this to someother table?


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

mavershang
Posting Yak Master

111 Posts

Posted - 2011-09-14 : 12:07:24
Not really, just a selection


quote:
Originally posted by visakh16

so you're trying to insert this to someother table?


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/



Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2011-09-14 : 12:42:51
I was goofing around and this seems to work if you only have 1 or 2 "duplicates." If you ahve more, then you'll need to do more to "uniqueify" the starting datasets:
DECLARE @Foo TABLE (C1 INT, C2 INT)

INSERT @Foo (C1, C2)
VALUES
(1, 100),
(2, 121),
(2, 130),
(121, 2),
(3, 99),
(99, 3),
(120, 10)


SELECT
C1,
C2,
RowNum
FROM
(
SELECT
A.C1,
A.C2,
(
ROW_NUMBER() OVER (ORDER BY A.C1, A.C2)
- ROW_NUMBER() OVER (ORDER BY B.C1, B.C2)
) AS RowNum
FROM
@Foo AS A
LEFT JOIN
@Foo AS B
ON A.C1 = B.C2
AND A.C2 = B.C1
) AS A
WHERE
RowNum >= 0
Go to Top of Page
   

- Advertisement -