0

Okay I have two tables: Table 1 looks like this:

id age gender
1   10   M
2   11   F
3   11   F

And Table 2 looks like this (same with different values):

id age gender
1  11   F
2  12   M
3  10   M

Now I want my final output to look like the following:

age count
10   2
11   3
12   1

What is the most efficient way to achieve this?

pewpewlasers
  • 3,025
  • 4
  • 31
  • 58

2 Answers2

6

You want to aggregate the union:

select age, count(*)
from (select id, age, gender from table1 union all
      select id, age, gender from table2
     ) t
group by age
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • hey thanks for your answer, works like a charm... if you have some time could you please check this out too? :D http://stackoverflow.com/questions/14641572/counting-and-grouping-same-named-column-in-different-tables-where-clause-from-o – pewpewlasers Feb 01 '13 at 07:31
  • 1
    @user1768337 . . . Whether you do the union/aggregation (as done here) or aggregation/union/aggregation is really a question of performance. For large data sets, I might be tempted to do the latter. – Gordon Linoff Feb 01 '13 at 15:11
0

try this

select age ,count(age) count from table1 group by age
union
select age, count(age)  count from table2 group by age
echo_Me
  • 37,078
  • 5
  • 58
  • 78