联合中的SQL和行

时间:2012-02-22 23:52:27

标签: mysql sql sum union

我正在尝试在UNION中从不同的SQL查询中获取两行,这可能吗? 我所能实现的只是两个独立的行,但我无法对它们进行求和,DB引擎让我告诉*)FROM(SUM旁边的部分)附近的语法中有错误...

以下是查询:

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

任何想法这个总和如何运作?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:6)

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

答案 2 :(得分:4)

你也可以使用:

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

答案 3 :(得分: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