How to in a Query Calculate the Sum of the Union

a simple way to sum a result from UNION in MySql

select id, sum(amount) from (
select id,amount from table_1 union all
select id,amount from table_2 union all
select id,amount from table_3
) x group by id

Sum union values

You can try using this in a subquery and calculate at the outer query. Ensure you use UNION ALL to evade the duplicate check

SELECT SUM(a) target_value
FROM
(SELECT
sum(target_value) a FROM table
UNION ALL
SELECT
sum(target_value) a FROM table_2) ;

SQL Query to sum multiple count union queries

You don't need window functions for that

select sum(cnt) as total
from
(
SELECT COUNT(col_x) as cnt FROM tablea
UNION
SELECT COUNT(col_y) FROM tableb
) tmp

Sum a union query

You need to alias your derived table, you must also use a group by with a having clause.

SELECT
q1.Period,
q1.PCC,
SUM(q1.BasicHits),
SUM(q1.FareHits),
SUM(q1.SearchHits)
FROM (SELECT
AAAPeriod AS Period,
AAAFromPCC AS PCC,
- SUM(AAABasic) AS BasicHits,
- SUM(AAAFare) AS FareHits,
- SUM(AAASearch) AS SearchHits
FROM HitsAaa
GROUP BY
AAAPeriod,
AAAFromPCC
HAVING (AAAPeriod = N'2010-10')

UNION ALL

SELECT
AAAPeriod AS Period,
AAAtoPCC AS PCC,
SUM(AAABasic) AS BasicHits,
SUM(AAAFare) AS FareHits,
SUM(AAASearch) AS SearchHits
FROM HitsAaa
GROUP BY
AAAPeriod,
AAAtoPCC
HAVING (AAAPeriod = N'2010-10')

UNION ALL

SELECT
AgtPeriod AS Period,
AgtPcc AS PCC,
SUM(AgtBasic) AS BasicHits,
SUM(AgtFare) AS FareHits,
SUM(AgtSearch) AS SearchHits
FROM HitsAgent
GROUP BY
AgtPeriod,
AgtPCC
HAVING (AgtPeriod = N'2010-10')) q1
GROUP BY
q1.Period,
q1.PCC

SQL sum rows in union

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


Related Topics



Leave a reply



Submit