-4

Given table

For this table each column has distinct rows i.e count(Name) = count(Spouse_Name) = count(*) Want to write a SQL query where pairs (Name and Spouse_Name) are distinct i.e Alex Sandra and Sandra Alex are same.

The output should be following:

Output must be this

Note: Self Inner Join if possible.

forpas
  • 160,666
  • 10
  • 38
  • 76
afghani
  • 467
  • 5
  • 7
  • 1
    Please specify what you have tried and what is the exact problem you are facing. – Yevgen Mar 13 '20 at 17:08
  • 1
    Have you tried anything??? – Eric Mar 13 '20 at 22:34
  • Please [use text, not images/links, for text--including tables & ERDs](https://meta.stackoverflow.com/q/285551/3404097). Use images only for what cannot be expressed as text or to augment text. Please in code questions give a [mre]--cut & paste & runnable code, including smallest representative example input as code; desired & actual output (including verbatim error messages); tags & versions; clear specification & explanation. For SQL that includes DBMS & DDL (including constraints & indexes) & input as code formatted as a table. Don't ask us to do your homework. – philipxy Mar 13 '20 at 22:48

2 Answers2

0

Assuming that name and spouse_name will never be equal in the same row you can use NOT EXISTS like this:

select t.*
from tablename t
where t.name < t.spouse_name
or not exists (
  select 1 from tablename
  where name = t.spouse_name and spouse_name = t.name
)

This code will work in any database since it uses standard SQL.
For MySql and this sample data you can do this self join:

select distinct
  least(t1.name, t1.spouse_name) name, 
  greatest(t1.name, t1.spouse_name) spouse_name
from tablename t1 inner join tablename t2
on t1.name = t2.spouse_name and t2.name = t1.spouse_name

Although the same results can be obtained without a join:

select distinct
  least(t1.name, t1.spouse_name) name, 
  greatest(t1.name, t1.spouse_name) spouse_name
from tablename t1

And another query with a self join:

select t1.name, t1.spouse_name 
from tablename t1 inner join tablename t2
on t2.spouse_name = t1.name and t2.name = t1.spouse_name 
where t1.name < t1.spouse_name 
forpas
  • 160,666
  • 10
  • 38
  • 76
0

Untested:

select distinct t1.name, t1.spouse_name
from table t1
inner join table t2
on concat(t1.name, t1.spouse_name) = concat(t2.spouse_name, t2.name)

I couldn't find the table name in your post so I used the name table.

Abra
  • 19,142
  • 7
  • 29
  • 41