2012-02-22 112 views
2

我想從SUM中的不同SQL查詢中獲取兩行SUM,這可能嗎? 所有我能達到的是兩個單獨的行,但我不能SUM他們,數據庫引擎讓我告訴,*)FROM(旁邊的部分)FROM附近的語法中有錯誤...聯合SQL總計行

這裏的查詢:

SELECT * FROM 

(SELECT COUNT(*) as cntclients                        
    FROM                              
    (SELECT DISTINCT clientkey AS clients                      
     FROM <table> 
    WHERE <conditions...>)                             
    ) AS clients                            
) cntclients 

UNION 

(SELECT SUM(occurrences) AS cntclientsad              
    FROM <table2> 
    WHERE <conditions...>          
) 

這引發了我,例如:

cntclients 
---------- 
901 
50 

添加SELECT SUM(*)FROM而不是SELECT * FROM在第一線,和周圍有括號中的兩個查詢只是拋出我提到的錯誤...

我想

cntclients <- or whatever name... 
---------- 
951 

任何想法,這筆錢應該如何工作?

回答

11

你實際上並不需要使用這個UNION - 你可以把它們相加手動:

SELECT a.countKey + b.sumOccur as total 
FROM (SELECT COUNT(DISINCT clientkey) as countKey 
     FROM <table> 
     WHERE <conditions>) as a 
CROSS JOIN (SELECT SUM(occurrences) as sumOccur 
      FROM <table2> 
      WHERE <conditions>) as b 
+0

您可以使用'CROSS JOIN'(不帶'ON')代替'JOIN ... ON 1 = 1'。 – 2012-02-23 00:13:25

+0

@ypercube - 謝謝 - 我經常不需要真正的笛卡爾產品,所以我忘了它。 – 2012-02-23 00:50:07

5
select SUM(cntcol) 
from 
(
    select count(*) as cntcol from sometables 
    union all 
    select SUM(occurrances) as cntcol from somemoretables 
) ctquery 
+0

你不需要'GROUP BY'來使用'SUM()'嗎? – 2012-02-23 00:02:45

+1

沒有。如果你想總結所有行,你爲什麼需要任何種類的分組? – 2012-02-23 00:05:10

3

如果你想用UNION堅持,你可以這樣寫:

SELECT sum(c.cntclients) as Totalcntclients 
FROM 
(

    SELECT COUNT(*) as cntclients                        
    FROM                              
    (SELECT DISTINCT clientkey AS clients                      
     FROM <table> 
    WHERE <conditions...>                             
    ) AS clients                            

    UNION 

    SELECT SUM(occurrences) AS cntclientsad              
    FROM <table2> 
    WHERE <conditions...>          

) c 
4

您還可以使用:

SELECT 
    (SELECT COUNT(DISTINCT clientkey) as countKey 
     FROM <table> 
     WHERE <conditions> 
    ) 
    + 
    (SELECT SUM(occurrences) as sumOccur 
     FROM <table2> 
     WHERE <conditions> 
    ) 
    AS total 
+1

有類似的問題,並感謝您的簡單回答我可以寫一個適當的查詢。謝謝。仍然,我想知道,爲什麼當我替換)+(爲聯合在查詢dosn't工作正常?文檔中沒有給我提供線索 – 2012-05-02 19:48:46

+1

如果你這樣做替換你有一個子查詢:'(SELECT cnt ... UNION SELECT ...)'這是一個有1列,2行的表格,你可以使用'SELECT SUM(cnt)FROM(SELECT cnt ... UNION SELECT ...)AS g'。沒有額外的聚合(SUM),因爲子查詢返回一列1行,你可以把這些子查詢放在選擇列表中。 – 2012-05-02 21:17:55