简体   繁体   English

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

[英]Using union and count(*) together in SQL query

I have a SQL query, looks something like this:我有一个 SQL 查询,看起来像这样:

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). (因此 group by 仍然可以正常运行)。 I tried with union all, however it won't work.我尝试与 union all 一起使用,但它不起作用。 What am I missing?我错过了什么?

SELECT tem.name, COUNT(*) 
FROM (
  SELECT name FROM results
  UNION ALL
  SELECT name FROM archive_results
) AS tem
GROUP BY name
ORDER BY name

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;

Is your goal...你的目标是...

  1. To count all the instances of "Bob Jones" in both tables (for example)计算两个表中“Bob Jones”的所有实例(例如)
  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?要在一行中计算Results中所有“Bob Jones”的实例,并将Archive_Results中的所有“Bob Jones”实例计算在单独的一行中?

Assuming it's #1 you'd want something like...假设它是#1,你会想要像......

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM