2017-05-30 45 views
0
Select Count(1) as COUNT1 from 
(
Select A,B from table1 
union 
Select A, B from table2 
) 
Select Count(1) as COUNT2 from 
(
Select C,D from table3 
union 
Select C,D from table4 
) 
Select Count(1) as COUNT3 from 
(
Select E,F from table5 
union 
Select E,F from table6 
); 

我想顯示一個表,顯示COUNT1,COUNT2,COUNT3。我想將各種SQL查詢的計數合併爲一個以顯示各列

+0

由於您只使用計數,因此只能從查詢返回單個數值。所以你可以外部連接這些來獲得所有三個計數的單行 –

+0

@SchmitzIT這不會給你3行而不是1行。 –

回答

1

試試這個:

SELECT SUM(COUNT1) AS COUNT1, SUM(COUNT2) AS COUNT2, SUM(COUNT3) AS COUNT3 
FROM 
(
    Select Count(1) as COUNT1, 0 AS COUNT2, 0 AS COUNT3 from 
    (
    Select A,B from table1 
    union 
    Select A, B from table2 
    ) 
    UNION ALL 
    Select 0 AS COUNT1, Count(1) as COUNT2, 0 AS COUNT3 from 
    (
    Select C,D from table3 
    union 
    Select C,D from table4 
    ) 
    UNION ALL 
    Select 0 AS COUNT1, 0 AS COUNT2, Count(1) as COUNT3 from 
    (
    Select E,F from table5 
    union 
    Select E,F from table6 
    ) 
) AS a 

從本質上講,你正在添加1個排,每源表,而對於非相關計數加0值。你最後在結果集上執行一個SUM,最後得到一個包含正確計數的單個行。

1
SELECT a.COUNT1 , 
    b.COUNT2, 
    c.COUNT3 
FROM 
    (SELECT COUNT(1) AS COUNT1 
    FROM 
    (SELECT A,B FROM table1 
    UNION 
    SELECT A, B FROM table2 
    ) 
) AS a, 
    (SELECT COUNT(1) AS COUNT2 
    FROM 
    (SELECT C,D FROM table3 
    UNION 
    SELECT C,D FROM table4 
    ) 
) AS b, 
    (SELECT COUNT(1) AS COUNT3 
    FROM 
    (SELECT E,F FROM table5 
    UNION 
    SELECT E,F FROM table6 
    ) 
) AS c;