tags:

views:

1132

answers:

4

Hello

I have a SQL query, looks something like this:

select name, count (*) from Results group by name order by name

and another, identical which loads from a archive results table, but the fields are the same.

select name, count (*) from Archive_Results group by name order by name

How would I combine the two in just one query? (So the group by would still function correctly). I tried with union all, however it won't work. What am I missing?

+2  A: 

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name
VoteyDisciple
+3  A: 
select tem.name, count(*) 
from(select name from results
union all
select name from archive_results) as tem
group by name
order by name
krdluzni
Thank you. All what I was missing was the "as tem" part ... Forgot that I have to name the "table" I create in order for this to work.
Rekreativc
This will give the wrong answer. In fact, it will give a count of 1 for every name, because UNION is by default UNION DISTINCT.Use UNION ALL.
Steve Kass
Thank you Steve Kass, however I already knew that I needed to use UNION ALL. As stated above all what I was missing was the "as" term.
Rekreativc
@Rekreativc: No problem. I commented because you marked the solution as Best Answer, and I didn't want future readers to think it was a correct answer.
Steve Kass
Fixed, and changed to community wiki.
krdluzni
A: 

Try this.

SELECT  * FROM
(
select name, count (*) Num from Results group by name
union ALL
select name, count (*) Num from Archive_Results group by name 
) A
order by name
RRUZ
+1  A: 

If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:

SELECT name, MAX(Rcount) + MAX(Acount) as TotalCount
FROM (
  SELECT name, count(*) as Rcount, 0 as Acount
  FROM Results GROUP BY name
  UNION ALL
  SELECT name, 0, count(*)
  FROM Archive_Results
  GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;
Steve Kass