Find a combination of values ​​on the same table in the sql server

advertisements

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.


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.