My existing SQL looks like the below, it will generate only the total_pending_req
count.
SELECT count(table1.employee_code) as total_requests, table1.employee_code as emp_code
FROM table1
WHERE employee_status = 'PENDING'
GROUP BY emp_code
UNION ALL
SELECT count(table2.employee_code) as total_requests, table2.employee_code as emp_code
FROM table2
WHERE employee_status = 'PENDING'
GROUP BY emp_code
UNION ALL
SELECT count(table3.employee_code) as total_requests, table3.employee_code as emp_code
FROM table3
WHERE employee_status = 'PENDING'
GROUP BY emp_code
This will return the result below,
I want to get the request count as total_pending_req
, total_rejected_req
and total_completed_req
considering 3 different tables. All tables have the same status codes, PENDING
, COMPLETED
and REJECTED
. The final result should be like this,
I would like to have an idea, of how to extract data more efficiently, since I have to use UNION ALL
. May I know if there is any better approach to extract data more efficiently? I would appreciate your help on this.
2
Answers
The fact that your rows appear in the
several table{1,2,3} relations is just
an annoying distraction.
Let’s make it a single relation, already.
We could create a table or a view.
Good!
With that out of the way, it becomes a trivial GROUP BY.
You can phrase it as a
CTE
if you’re averse to DDL.
Or create a VIEW that does the UNION ALL heavy lifting.
Or a MATERIALIZED VIEW, whatever.
The output format is three emps × three statuses,
or nine rows.
If you really need three rows, feel free to SELECT
from that relation to re-format it.
you can use
CASE
andUnion All
as followsOr using
SUM
andCase