6 years ago
8/4/17
Control sort in union all
If you have a union all select statement and you want to have the results from the first select statement first and second statement second, etc..... here what you can do.
let's say we are getting the employee names from different tables
select employee_name from company1
union all
select employee_name from company2
union all
select employee_name from company3
union all
select employee_name from company4
union all
select employee_name from company5
order by 1;
In this select statement all employee will be mixed from all companies sorted by name, but what if you want to have the name of the employee from company1 first and then from company2 and then from company3 etc.....
Here what you can do
select 'A',employee_name from company1
union all
select 'B',employee_name from company2
union all
select 'C',employee_name from company3
union all
select 'D', employee_name from company4
union all
select 'E', employee_name from company5
order by 1,2;
This way the employee will be sorted by name from company1 first and then second, etc....
If you have the select statement in SQL*Plus and you don't want to show this extra column here what you can do:
column sort1 noprint --- this will hide column sort1
select 'A' sort1,employee_name from company1
union all
select 'B' sort1,employee_name from company2
union all
select 'C' sort1,employee_name from company3
union all
select 'D' sort1, employee_name from company4
union all
select 'E' sort1, employee_name from company5
order by 1,2;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment