如何将多个SQL查询相加?

时间:2021-08-13 15:51:15

I'm trying to run multiple queries on multiple tables- similar to "select count(*) from TableA where x=1" per table.

我正在尝试在多个表上运行多个查询 - 类似于“从TableA中选择count(*),其中x = 1”每个表。

What I'd like to do, is get all of the count(*) values that are returned and sum them into a single value...

我想做的是获取返回的所有count(*)值并将它们加总为单个值...

Any ideas?

有任何想法吗?

2 个解决方案

#1


11  

select sum(individual_counts) from
(
  select count(*) as individual_counts from TableA where x = 1
    union all
  select count(*) from TableB where x = 2
....
) as temp_table_name

you normally only need the alias on the first select when using a union.

在使用联合时,通常只需要第一个选择的别名。

#2


8  

Not 100% sure what you mean, but maybe:

不是100%肯定你的意思,但也许:

SELECT (SELECT COUNT(*) FROM tableA)+(SELECT COUNT(*) FROM tableB)

#1


11  

select sum(individual_counts) from
(
  select count(*) as individual_counts from TableA where x = 1
    union all
  select count(*) from TableB where x = 2
....
) as temp_table_name

you normally only need the alias on the first select when using a union.

在使用联合时,通常只需要第一个选择的别名。

#2


8  

Not 100% sure what you mean, but maybe:

不是100%肯定你的意思,但也许:

SELECT (SELECT COUNT(*) FROM tableA)+(SELECT COUNT(*) FROM tableB)