在SQL查询中一起使用union和count(*)

时间:2009-08-12 14:48:08

标签: sql union

我有一个SQL查询,看起来像这样:

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

和另一个相同的,从归档结果表中加载,但字段是相同的。

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

如何在一个查询中将两者结合起来? (因此,群组仍将正常运作)。我尝试使用union all,但是它不起作用。我错过了什么?

4 个答案:

答案 0 :(得分:68)

select tem.name, count(*) 
from(select name from results
union all
select name from archive_results) as tem
group by name
order by name

答案 1 :(得分:9)

如果您有支持索引和相对较高的计数,这样的事情可能比建议的解决方案快得多:

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;

答案 2 :(得分:7)

你的目标是......

  1. 计算“鲍勃的所有实例” 琼斯“在两个表格中(例如)
  2. 计算“鲍勃的所有实例” 琼斯“在Results中排成一排 所有“鲍勃琼斯”的实例 Archive_Results在另一行?
  3. 假设它是#1你想要的东西......

    SELECT name, COUNT(*) FROM
    (SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
    GROUP BY name
    ORDER BY name
    

答案 3 :(得分:0)

select T1.name, count (*)
from (select name from Results 
      union 
      select name from Archive_Results) as T1
group by T1.name order by T1.name