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 2000 Forums
 Transact-SQL (2000)
 SUM a SUM

Author  Topic 

ramoneguru
Yak Posting Veteran

69 Posts

Posted - 2006-10-12 : 21:43:02
Ok, here's my problem. I need something like a grand total from a summary field that looks like this:


Asian 0 0 0 0 9 22 18 9 10 0 68
Black 0 0 2 0 14 12 11 0 4 7 50
Hispan 0 0 0 0 12 5 5 6 0 0 28
Native 0 0 0 0 0 2 3 3 0 0 8
N/A 0 0 0 0 0 3 2 0 0 0 5
Pacific 1 0 0 0 3 0 0 2 0 0 6
White 0 0 4 0 16 21 17 9 9 8 84



The code to generate this looks like this:

SELECT vd.Ethnicity,
SUM(CASE WHEN vd.Age >= 16 AND vd.Age <= 18 AND vd.Gender = 'Male' THEN 1 ELSE 0 END) AS Mage1,
SUM(CASE WHEN vd.Age >= 16 AND vd.Age <= 18 AND vd.Gender = 'Female' THEN 1 ELSE 0 END) AS Fage1,

SUM(CASE WHEN vd.Age >= 19 AND vd.Age <= 24 AND vd.Gender = 'Male' THEN 1 ELSE 0 END) AS Mage2,
SUM(CASE WHEN vd.Age >= 19 AND vd.Age <= 24 AND vd.Gender = 'Female' THEN 1 ELSE 0 END) AS Fage2,

--rest of them look the same

--Will sum along the rows
SUM(CASE WHEN (vd.Age >= 16) AND (vd.Gender = 'Female' OR vd.Gender = 'Male') THEN 1 ELSE 0 END) AS TotalAge
FROM ViewDemographics vd
GROUP BY vd.Ethnicity


Now, I can't figure out how to get a total per column and a grand total......Little help.
--Nick

ramoneguru
Yak Posting Veteran

69 Posts

Posted - 2006-10-12 : 22:03:19
Ok, got a grand total:
(SELECT COUNT(PersonID) FROM ViewDemographics WHERE Age >= '16') AS 'Total'

Just need a column count for each column....
--Nick
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2006-10-12 : 22:26:09
Did you try this?

GROUP BY vd.Ethnicity WITH ROLLUP


CODO ERGO SUM
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2006-10-13 : 08:43:54
>>I can't figure out how to get a total per column and a grand total......Little help.

If you use Reports, you can generate subtotal there
Otherwise Read about ROLLUP and CUBE in sql server help file

Madhivanan

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

ramoneguru
Yak Posting Veteran

69 Posts

Posted - 2006-10-13 : 15:23:07
Wonderful, works like a charm. My report designer (Active Reports) was just being quite a hassle while I was adding the sums. Thanks again, simply adding "WITH ROLLUP" in the group by statement worked out.
--Nick
Go to Top of Page
   

- Advertisement -