Link to home
Start Free TrialLog in
Avatar of baxtalo
baxtalo

asked on

SQL Percentage

Hi Experts,
I use the query below to display the total number of different topics from my table on a pie chart .
Select COUNT(*) as [Count], Topic FROM [myDatabase].[dbo].[myTable] group by Topic

I would like to display the percentage instead of the count. How could I achieve that?
Thanks for your help.
ASKER CERTIFIED SOLUTION
Avatar of Ashok
Ashok
Flag of United States of America 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
SOLUTION
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
You can try this...

Select (COUNT(*)/100)*100 as [Count], Topic FROM [myDatabase].[dbo].[myTable] group by Topic
Avatar of baxtalo
baxtalo

ASKER

Thank you very much, your comments helped. After trying everything possible I settled with this one:

      declare @total decimal

      select @total = COUNT(*)
      FROM [myDatabase].[dbo].[myTable]

      Select COUNT(*) as [Count], cast(COUNT(*)/@total*100 as numeric(10,0)) as [Percentage], Topic
      FROM [myDatabase].[dbo].[myTable]
      group by Letter
You may want to include that if statement as you have a potentional divide by zero error if MyTable has no rows.