Home » Php » PHP MySql percentage

PHP MySql percentage

Posted by: admin July 12, 2020 Leave a comment

Questions:

My question is about percentages, I’m not an expert so I will try to explain in the better possible way.

I have a table with, let say 700 records, in my mysql server, something like this

+-------+---------+----------+-------+
| Name  | country | language | Birth |
+-------+---------+----------+-------+
| Lucy  | UK      | EN       | 1980  |
| Mari  | Canada  | FR       | 1990  |
| Gary  | Canada  | EN       | 1982  |
| Stacy | Jamaica | EN       | 1986  |
| Joao  | Brasil  | PT       | 1984  |
+-------+---------+----------+-------+

So I query all the records that are between 1980 and 1985 and the result will be:

+------+---------+----------+-------+
| Name | country | language | Birth |
+------+---------+----------+-------+
| Lucy | UK      | EN       | 1980  |
| Gary | Canada  | EN       | 1982  |
| Joao | Brasil  | PT       | 1984  |
+------+---------+----------+-------+

and from this result I would like to obtain:

  1. the percentage of appearance of every languages between those years

    EN = 75% (3 is the total in this case)
    PT = 25%
    
  2. the percentage of appearance of every country that is seen in the resulting table

    UK = 33%
    Canada = 33%
    Brasil = 33%
    

I mean how can I convert the results in variables to use them in the final function.

How to&Answers:

This may work, but something along the line of:

set @total_rows = (SELECT COUNT(*) FROM table WHERE Birth between 1980 and 1985);

SELECT language, percentage
FROM (
    SELECT language, concat(count(language)/@total_rows, "%") AS percentage 
    FROM table WHERE Birth between 1980 and 1985
)

Answer:

I’ll answer here as doing SQL in a comment isn’t too comfortable.

To have your percentages you just need to take your previous output as a view and add the percentage column, this should do :

select NAME, QUANTITY, QUANTITY/(select count(1) from TABLE) as PERCENTAGE
from (
    select NAME, count(1) as QUANTITY
    from TABLE
    where condition
    group by NAME
)

But this is not really optimized since you call a count on whole table everytime you wanna fetch a single row, and even if MySQL will index results of count, it still won’t be the best.

What you should do is to first get the total size of the table into your php :

select count(1) as totalsize
from TABLE

Then to use it in your next request :

select NAME, QUANTITY, QUANTITY/[totalsize from php] as PERCENTAGE
from (
    select NAME, count(1) as QUANTITY
    from TABLE
    where condition
    group by NAME
)