user0000001
user0000001

Reputation: 2233

MySQL: Get the average of a column

I have a table name invoices. There is a column named user and late_fee. I am trying to find out the percentage of late invoices compared to how many invoices total.

He has 16 invoices, which 2 of those invoices are late. I feel like this should be an easy pie query but I can't figure it out for the life of me?

Upvotes: 0

Views: 80

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157118

You could use something like this. It gets the count of the late_fee depending on it's value.

select sum( case
            when late_fee = 1
            then 1
            else 0
            end
          )
        / count(*)
from    invoices
group
by      user

As @Ravinder pointed out, in MySQL this is also valid (does not work on other platforms though):

select sum( late_fee = 1
          )
        / count(*)
from    invoices
group
by      user

Upvotes: 5

Related Questions