Search code examples
sqlrecursive-query

How to compare all row values of a column against all different values of that column using SQL and return in seperate columns


I have a column that has values like this I want to write an SQL statement to return values in two columns which will look like this.

[input] [1]: https://i.sstatic.net/j5GuT.png


[Output] [2]: https://i.sstatic.net/JHolu.png


Solution

  • You just need to self JOIN your table with column value unequality condition like this

    WITH data AS (
        SELECT * FROM (values ('a'), ('b'), ('c'), ('d')) t("column")
    )
    SELECT d1."column", d2."column"
    FROM data d1
    JOIN data d2 ON d1."column" != d2."column"
    ORDER BY 1, 2