|
There are two ways.
select category2, category3, category4
, count(*) as overall_count
from (
select category2, category3, category4
from table1
UNION ALL
select category2, category3, category4
from table2
) as d
group by category2, category3, category4
The first way, all the detail rows are combined by the
UNION subquery, and then the outer query just takes totals.
select category2, category3, category4
, sum(subtotal) as overall_count
from (
select category2, category3, category4
, count(*) as subtotal
from table1
group by category2, category3, category4
UNION ALL
select category2, category3, category4
, count(*) as subtotal
from table2
group by category2, category3, category4
) as d
group by category2, category3, category4
The second way, subtotals are prepared for each table, then summed.
Notice that the first query has only one GROUP BY,
whereas the second has three. Which of these do you think will be
more efficient? Which SQL will be easier to maintain?
|