Let’s say we have a couple of simple SQL queries, one of which counts the total number of job hours:
select sum(Hours) as totalCount from job_details where Job_ID = 42504;
and another query that sums the total number of job hours that have been completed:
select sum(Hours) as completedCount from job_details where Job_ID = 42504 and Completed = 1;
If we want to combine both of these queries into a single query, we can! The trick is to use aliases for both of the selects.
For example, here I have used the aliases “as a” and “as b”:
select totalCount, completedCount from (select sum(Hours) as totalCount from job_details where Job_ID = 42504) as a, (select sum(Hours) as completedCount from job_details where Job_ID = 42504 and Completed = 1) as b;
Here is an example of wrapping 5 SQL queries into one:
select total, completed, dept_id, deptName, schedStart, schedEnd, numTasks from (select sum(details.Hours) as total from job_details details, job_schedule sched where details.Job_ID = '41230' and sched.Shop_ID = '9553' and details.Job_ID = sched.Job_ID) as a, (select sum(details.Hours) as completed from job_details details, job_schedule sched where details.Job_ID = '41230' and details.Completed = 1 and sched.Shop_ID = '9553' and details.Job_ID = sched.Job_ID) as b, (select store.Dept_ID as dept_id, website.Department as deptName from store.job_details store, job_schedule sched, website.customer_service_department website where store.Job_ID = '41230' and sched.Shop_ID = '9553' and store.Completed = 0 and store.Dept_ID = website.ID and store.Job_ID = sched.Job_ID) as c, (select Scheduled_Start as schedStart, Scheduled_End as schedEnd from job_schedule sched where Job_ID = '41230' and Shop_ID = '9553') as d, (select count(Description) as numTasks from job_details where Job_ID = '41230') as e;
Notes:
- Each of the columns in the output are listed in the inital select at the top of the overall query. For example, the first column “total” is returned by the first query “a”.
- In the FROM portion of the overall query, there are 5 sub-queries, with aliases a – e.
- Each sub-query starts with select and is wrapped in parenthesis.
- The output of each sub-query feeds the top level selects.
- It is possible for a sub-query to return more than one output. For example sub-query c returns both dept_id and deptName.