Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 HOW to the SUM of a field from a UNION

Author  Topic 

khovorka
Starting Member

8 Posts

Posted - 2014-03-19 : 12:23:47
Hello,

I have not worked with Unions before and so this is my first attempt and I am getting an error near the UNION line. Any Help is appreciated:

SELECT patientid, SUM(CAST(tot_steps AS int)) AS totsteps
FROM workouts
WHERE patientid IN (12345) AND updated >= '2014-04-11' AND CAST(tot_steps AS int) > 0
GROUP BY patientid
ORDER BY totsteps DESC
UNION ALL
SELECT patientid, SUM(CAST(steps AS int)) AS totsteps
FROM exercises_weekly
WHERE patientid IN (12345) AND timestamp >= '2014-04-11' AND CAST(steps AS int) > 0
GROUP BY patientid
ORDER BY totsteps DESC

Kim H.

VeeranjaneyuluAnnapureddy
Posting Yak Master

169 Posts

Posted - 2014-03-20 : 00:33:26
SELECT patientid, SUM(CAST(tot_steps AS int)) AS totsteps
FROM workouts
WHERE patientid IN (12345) AND updated >= '2014-04-11' AND CAST(tot_steps AS int) > 0
GROUP BY patientid
--ORDER BY totsteps DESC
UNION ALL
SELECT patientid, SUM(CAST(steps AS int)) AS totsteps
FROM exercises_weekly
WHERE patientid IN (12345) AND timestamp >= '2014-04-11' AND CAST(steps AS int) > 0
GROUP BY patientid
ORDER BY totsteps,patientid DESC

Veera
Go to Top of Page
   

- Advertisement -