Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - percentage of total rows

I have this query:

SELECT 
Count(*) as Cnt, 
Category
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

It gives me count of rows in each Category. Now I would like to add a third column that would give me Cnt / (total rows in this table).

How can I do that?

like image 629
ojek Avatar asked Oct 16 '25 14:10

ojek


2 Answers

As a note, you can actually do this with one query by using window functions:

SELECT Count(*) as Cnt, Category,
       cast(Count(*) as float) / sum(count(*)) over () as ThirdColumn
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
like image 78
Gordon Linoff Avatar answered Oct 18 '25 08:10

Gordon Linoff


you could do it with a subquery:

SELECT Count(*) as Cnt, Category, 
  (Cast(Count(*) as real) / cast((SELECT Count(*) FROM [MyDb].[dbo].[MyTable]) as  real)) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

or with a variable:

declare @total real;
select @total = count(*) from [MyDb].[dbo].[MyTable];

SELECT Count(*) as Cnt, Category, (Cast(Count(*) as real) / @total) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

I've cast count(*) as real in both examples to avoid integer-division type issues.

Hope this helps John

like image 21
John Bingham Avatar answered Oct 18 '25 06:10

John Bingham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!