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 2005 Forums
 Transact-SQL (2005)
 sum of a union

Author  Topic 

edp33
Starting Member

9 Posts

Posted - 2008-02-05 : 06:55:45
I am using this query

SELECT RCME_Projects.ProjectReference,1 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>0 AND RCME_Projects.TotalDays<=10
union
SELECT RCME_Projects.ProjectReference,2 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>10 AND RCME_Projects.TotalDays<=21
union
SELECT RCME_Projects.ProjectReference,3 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>21

To get the following output

ProjectReference,Number
2048,1
2341,2
1234,1
2345,1
2313,3
etc

I would like to get the SUM of the number column, but can't find a way to get the sum of a union. In mysql it appears you can do it using
SELECT sum(number) from
{
/* union query here */
} as total
but that doesn't seem to work for sql server 2005, would really appreciate any help!


ayamas
Aged Yak Warrior

552 Posts

Posted - 2008-02-05 : 06:57:49
Change braces {} with brackets () also write
select sum(number) from
(
Union query

)T
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-02-05 : 06:59:55
SELECT sum(number) from
(
SELECT RCME_Projects.ProjectReference,1 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>0 AND RCME_Projects.TotalDays<=10
union
SELECT RCME_Projects.ProjectReference,2 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>10 AND RCME_Projects.TotalDays<=21
union
SELECT RCME_Projects.ProjectReference,3 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>21

)
Go to Top of Page

edp33
Starting Member

9 Posts

Posted - 2008-02-05 : 07:02:58
Thanks so much, it was missing the T at the end !!!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-02-05 : 08:05:29
quote:
Originally posted by edp33

I am using this query

SELECT RCME_Projects.ProjectReference,1 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>0 AND RCME_Projects.TotalDays<=10
union
SELECT RCME_Projects.ProjectReference,2 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>10 AND RCME_Projects.TotalDays<=21
union
SELECT RCME_Projects.ProjectReference,3 As Number
FROM RCME_Projects
WHERE RCME_Projects.TotalDays>21

To get the following output

ProjectReference,Number
2048,1
2341,2
1234,1
2345,1
2313,3
etc

I would like to get the SUM of the number column, but can't find a way to get the sum of a union. In mysql it appears you can do it using
SELECT sum(number) from
{
/* union query here */
} as total
but that doesn't seem to work for sql server 2005, would really appreciate any help!





Im MySQL also you need to use () in place of {}

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -