1

The code below works fine up till the point i try to order it by name.

first time working with union so little confused on how to order these tables together when the first column names are different.

SELECT 
    e.emp_name 'Name',
    e.emp_gen 'Gender',
    ('Employee') 'Role'
FROM employee e
ORDER BY e.emp_name ASC
        UNION ALL
SELECT 
    s.sup_name 'Name',
    s.gen 'Gender',
    ('Supervisor') 'Role'
FROM supervisor s
ORDER BY s.sup_name ASC;

EDIT

have now tried this but doesn't seem to work as well

SELECT 
    e.emp_name 'Name',
    e.emp_gen 'Gender',
    ('Employee') 'Role'
FROM employee e
        UNION ALL
SELECT 
    s.sup_name 'Name',
    s.gen 'Gender',
    ('Supervisor') 'Role'
FROM supervisor s
ORDER BY s.sup_name ASC;

2 Answers2

0

Figured it out.

everything was working fine like i said up till the 'order by', i think because of the fact that the name columns for the two tables were different so i changed the order by statement to reference the column.

i forgot you could do this.

also i did not mean to have union 'all' this was something i was just playing around with while stuck.

sorry if i confused people with that union all

SELECT 
    e.emp_name 'Name',
    e.emp_gen 'Gender',
    ('Employee') 'Role'
FROM employee e
        UNION
SELECT 
    s.sup_name 'Name',
    s.gen 'Gender',
    ('Supervisor') 'Role'
FROM supervisor s
ORDER BY 1 ASC;
  • ORDER BY 'Name' ASC is better. (Order by ordinal position is deprecated.) Why ( )s around 'Employee' and 'Supervisor'? Why UNION instead of UNION ALL? – jarlh Jun 08 '15 at 05:29
0

It should be possible to order by name itself like below.

SELECT EMPNAME AS COL1, DOB FROM #TABLE1
UNION
SELECT SUPNAME AS COL1, DOB FROM #TABLE2
ORDER BY COL1

Or

SELECT EMPNAME 'COL1', DOB FROM #TABLE1
UNION
SELECT SUPNAME 'COL1', DOB FROM #TABLE2
ORDER BY COL1
Viswas Menon
  • 310
  • 3
  • 11