Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using union and count(*) together in SQL query

Tags:

sql

union

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?

like image 831
David Božjak Avatar asked Aug 12 '09 14:08

David Božjak


People also ask

How do you count a UNION query?

Here is the query to count on the union query. mysql> select count(*) as UnionCount from -> ( -> select distinct UserId from union_Table1 -> union -> select distinct UserId from union_Table2 -> )tbl1; The following is the output displaying the count.

Can we use UNION and join together in SQL?

SQL UNION with Inner Join The queries are two inner join statement. In the first query, the join takes place between two tables where the prod_code of both tables are same and in the 2nd query the join take place between two tables where the prod_name of both tables are same.


1 Answers

SELECT tem.name, COUNT(*)  FROM (   SELECT name FROM results   UNION ALL   SELECT name FROM archive_results ) AS tem GROUP BY name ORDER BY name 
like image 185
3 revs, 2 users 58% Avatar answered Sep 23 '22 21:09

3 revs, 2 users 58%