Home > Net >  Compare and print data from two columns in sql
Compare and print data from two columns in sql

Time:06-13

I have an employee table(emp). Sample data from emp table:

emp_name contact1 contact2
Harish  123      123
Manish  345      567
Ganesh  678      678

And the output I want is like below:

Harish  123
Ganesh  678
Manish  345
Manish  567

Explanation: It is like each employee has two contact number. If contact1 and contact2 are similar just return the output in a row but if in case contact1 and contact2 are different then return name and contact in two different rows as shown for emp_name "Manish".

Any suggestions on how this can be done ?

CodePudding user response:

You can do a UNION over the selection of the two columns separately, as follows:

SELECT emp_name, contact1 AS contact
FROM emp
UNION
SELECT emp_name, contact2 AS contact
FROM emp

Check the demo here.

Note: if you want, you can add an ORDER BY clause at the end to sort your rows.

  • Related