Search code examples
mysqlsqlsumunion

SQL sum rows in union


I'm trying to SUM two rows obtained from differente SQL queries in UNION, is this possible? All I can achieve is the two separate rows but I can't SUM them, DB engine keeps me telling that there's an error in the syntax near the *) FROM (the part next to the SUM)...

Here's the query:

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...>                                     
)

This throws me for example:

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

Adding a SELECT SUM(*) FROM instead of the SELECT * FROM in the first line, and surrounding the two queries with parentheses just throws me the mentioned error...

I would like

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

Any ideas how this sum should work?


Solution

  • You don't actually need to use a UNION for this - you can just add them together manually:

    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