Reputation: 463
I have tables that contain same field, for example:
p_central_ticket p_south_ticket p_west_ticket
=====================================================================
- t_id - t_id - t_id
- t_req_type - t_req_type - t_req_type
- t_status - t_status - t_status
And i have one table :
m_event_type
=============
- ev_type
- ev_activity
My current query :
SELECT ev_activity AS Activity, COUNT( * ) AS Total
FROM m_event_type
LEFT JOIN p_central_ticket ON p_central_ticket.t_req_type = m_event_type.ev_type
WHERE t_status =9
GROUP BY ev_activity
Output from query above:
My question is, how should i do, if i want to total count from 3 tables above.
(For Example Activity Change Request total 18000, count from p_central_ticket + p_south_ticket + p_west_ticket) etc.
Thanks...
Upvotes: 1
Views: 55
Reputation: 976
Use a UNION ALL (to avoid removing duplicates) then SUM the quantities Note that it also works if your tables have different column names you only need to alias them in the select.
SELECT ev_activity AS Activity, SUM(quantity) AS Total
FROM m_event_type met
LEFT JOIN (SELECT c.t_req_type, COUNT(*) as quantity
FROM p_central_ticket c
WHERE c.t_status =9
GROUP BY c.t_req_type
UNION ALL
SELECT s.t_req_type, COUNT(*)
FROM p_south_ticket s
WHERE s.t_status =9
GROUP BY s.t_req_type
UNION ALL
SELECT w.t_req_type, COUNT(*)
FROM p_west_ticket w
WHERE w.t_status =9
GROUP BY w.t_req_type) p ON
p.t_req_type = met.ev_type
GROUP BY ev_activity
Upvotes: 1
Reputation: 133400
You could use UNION ALL for select all the rows of the 3 tables
SELECT ev_activity AS Activity, COUNT( * ) AS Total
FROM m_event_type
LEFT JOIN (
select t_id, t_req_type, t_status
from p_central_ticket
union all
select t_id, t_req_type, t_status
from p_south_ticket
union all
select t_id, t_req_type, t_status
from p_west_ticket
) t ON t.t_req_type = m_event_type.ev_type
WHERE t.t_status =9
GROUP BY ev_activity
Upvotes: 0
Reputation: 11205
Use union all
in a subquery, then join it:
select t1.ev_Activity, count(t1.*) as total
from m_event_type t1
LEFT JOIN
(
select *
from p_central_ticket
WHERE t_status =9
union all
select *
from p_south_ticket
WHERE t_status =9
union all
select *
from p_west_ticket
WHERE t_status =9
) t2
ON t2.t_req_type = t1.ev_type
GROUP BY t1.ev_activity
Upvotes: 1