Link to home
Start Free TrialLog in
Avatar of HLyder
HLyderFlag for United States of America

asked on

SQL UNION AGGREGATE FUNCTION

I am creating an SQL query which (simplified) looks like

SELECT SUM(quantity) FROM ItemSales
WHERE UnitID = 1
UNION
SELECT SUM(quantity) FROM ProductionLoss
WHERE UnitID = 1

The above would give me a table with 2 lines, one for each select.
Question: How can I get an aggregate result yielding only a single result as the sum of the 2 rows produced.

Is there a way to do this without using temporary tables and stored procedures.

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

here we go:
SELECT SUM(Total) 
FROM ( SELECT SUM(quantity) Total FROM ItemSales
WHERE UnitID = 1
UNION ALL
SELECT SUM(quantity) FROM ProductionLoss
WHERE UnitID = 1
)

Open in new window

Avatar of HLyder

ASKER

Yes it looks just like what I am looking for but the query is returning an error message indicating incorrect syntax from the [Microsoft ODBC SQL Server Driver] pointing to the last ) in the statement.  
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HLyder

ASKER

you rock, thanks