[英]SQL: Combine Select count(*) from multiple tables
如何將來自不同表的多個選擇計數(*)組合成一個回報?
我和這篇文章有類似的情結
但我想要一次回歸。
我嘗試了所有的聯盟,但它吐了3個不同的計數行。 你如何將它們合二為一?
select count(*) from foo1 where ID = '00123244552000258'
union all
select count(*) from foo2 where ID = '00123244552000258'
union all
select count(*) from foo3 where ID = '00123244552000258'
編輯:我在MS SQL 2005上
SELECT
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')
這是一種簡單的方法。
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
我很驚訝沒有人建議這種變化:
SELECT SUM(c)
FROM (
SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258'
UNION ALL
SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258'
);
基本上,您將計數作為標准選擇中的子查詢。
一個例子如下,這將返回1行,兩列
SELECT
(SELECT COUNT(*) FROM MyTable WHERE MyCol = 'MyValue') AS MyTableCount,
(SELECT COUNT(*) FROM YourTable WHERE MyCol = 'MyValue') AS YourTableCount,
你可以像以前那樣合並你的計數,但是你可以通過多種方式對它們進行總結,其中一種如下所示:
SELECT SUM(A)
FROM
(
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
UNION ALL
SELECT 1 AS A
) AS B
您可以命名所有字段並在這些字段上添加外部選擇:
SELECT A, B, C FROM ( your initial query here ) TableAlias
這應該夠了吧。
select sum(counts) from (
select count(1) as counts from foo
union all
select count(1) as counts from bar)
對於oracle:
select(
select count(*) from foo1 where ID = '00123244552000258'
+
select count(*) from foo2 where ID = '00123244552000258'
+
select count(*) from foo3 where ID = '00123244552000258'
) total from dual;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.