May 26, 2010 at 9:48 pm
Can anyone tell me why this query is not working? The PercentofTotal column always returns all 0's. Thanks.
SELECT ColumnA, COUNT(ColumnB) AS TotalApps,
100. * (COUNT(ColumnB) / (SELECT COUNT(*) FROM Table)) AS PercentofTotal
FROM Table
GROUP BY ColumnA
ORDER BY TotalApps, PercentofTotal ASC
GO
May 26, 2010 at 10:23 pm
You need to cast the COUNT to DECIMAL/NUMERIC ;
try this:
SELECT ColumnA, COUNT(ColumnB) AS TotalApps ,
(100.00 * (cast(COUNT(ColumnB) as numeric(5,2)) / (select COUNT(*) FROM @table) )) AS PercentofTotal
FROM @table
GROUP BY ColumnA
ORDER BY TotalApps, PercentofTotal ASC
May 27, 2010 at 11:36 am
I'm now getting an error 8115, Arithmetic overflow converting int to data type numeric
May 27, 2010 at 4:04 pm
You can grab a percentage this way...
select (select cast(COUNT(ColumnB) as decimal) / (SELECT COUNT(*) FROM Table)
FROM from table) * 100 as PercentofTotal
May 28, 2010 at 8:35 am
If you're trying to create a result set from a single select then my suggestion won't work, but you could use a variable to achieve this:
declare @countOfAll decimal(5, 2)
select @countOfAll = COUNT(*) from Table
SELECT ColumnA, COUNT(ColumnB) as TotalApps,
COUNT(ColumnB) / @countofAll * 100 AS PercentofTotal
FROM Table
GROUP BY ColumnA
ORDER BY TotalApps, PercentofTotal ASC
GO
This has the added bonus of returning the answer in decimal format without casting since the variable is declared as decimal.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply