Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MySql percentage

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.

like image 498
Andrés Chandía Avatar asked Oct 04 '12 13:10

Andrés Chandía


People also ask

What is %s and %D in MySQL?

12 years, 11 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

How do I find the percentage of a column in MySQL?

To calculate percentage of column in MySQL, you can simply cross join the sum() of sale column with the original table. If you want to add a where clause to filter your data, you need to place it after the CROSS JOIN, as shown below. Otherwise, you will get an error.

Which country has the highest percentage of PHP?

Shares of PHP as primary programming language by country or region. The popularity of PHP is still the highest in France: 43% of French developers use it as a primary language, which is 5 percentage points more than last year.


1 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
)
like image 167
Mike Mackintosh Avatar answered Sep 28 '22 01:09

Mike Mackintosh