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
Sql Join: Selecting the Last Records in a One-To-Many Relationship
How to Get Last 7 Days Data from Current Datetime to Last 7 Days in SQL Server
Avoid Duplicates in Insert into Select Query in SQL Server
How to Execute a Stored Procedure Once for Each Row Returned by Query
How to Select Multiple Values in One Field MySQL
Show Zero If There Is No Record Count - Oracle SQL Query
Sql to Find Upper Case Words from a Column
State Wise Data of Country and City
Sql Query Is Taking More Than 4 Minutes
Run a Join Statement That Excludes Duplicate Rows
How to Pass Parameter to Mssql Query in Node Js
Removing Null Value in SQL Join and Union Operators in SQL
How to Get Calendar Quarter from a Date in Tsql
How to Get Only One Row Against Each Id in MySQL
Postgresql Convert Columns to Rows Transpose
Jsonb Array Contains Like or and and Operators
Sql Select Radius Search Based on Latitude Longitude
Oracle SQL Get the First and Last Records from an Ordered Dataset