1

I have a table like this:

Id  Name
1    x
2    y
3    z

I want a combination like:

Name    Name
x        y
x        z
y        z

this combination should be made from the same table. I tried the query like:

SELECT a.Name, b.Name
FROM table1 a, table1 b
WHERE a.Id != b.Id;

but this produce the result:

Name    Name
y        x
z        x
x        y
z        y
x        z
y        z

which one is not the exact result.

1
  • Try using a.Id < b.Id instead. Commented Apr 27, 2015 at 6:29

2 Answers 2

4

Try using < instead of !=:

SELECT 
    a.Name, 
    b.Name
FROM table1 a
INNER JOIN table1 b
    ON a.Id < b.Id

Note: Avoid using the old-style JOIN syntax.

Sign up to request clarification or add additional context in comments.

Comments

0
declare @t table (id int,name varchar(1))
insert into @t (id,name)values (1,'X'),(2,'Y'),(3,'Z')
;WITH Cte AS(
    SELECT *, 
        RN = ROW_NUMBER() OVER(ORDER BY name)
    FROM @t
)
SELECT 
     t1.name,
     t2.name
FROM Cte c
INNER JOIN Cte cc
    ON cc.RN > c.RN
    AND cc.name != c.name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.