Skip to content
Advertisement

MySQL query – addition, count and divide in one query

I have a table with column “Score”, which holds a number ranging from 1 to 10. I need to achieve the following calculation in MySQL:

Calculation: (Count of all scores >= 8) / (Count of all scores)

Calculation: (4) / (5)

Result: 0.8

Result in percent: 80%

How can I achieve this in as little queries as possible to get the result of “80%”?

Advertisement

Answer

You could do that with this query:

It relies on the fact that MySQL treats boolean values as either 1 or 0 in a numeric context, so for every Score >= 8 we add one to the SUM.

Demo on dbfiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement