Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column sum and use to calculate percent of total (mySQL)

Tags:

mysql

Here is a very basic look at my table. I have columns 1 and 2 and need to generate column 3. Column 3 is simply the total of the Number column for all Name divided by Number for the given row.

| Name          | Number        | % of total  |
| ------------- |:-------------:| -----:      |
| Bob           | 5             |  25         |
| Sally         | 10            |  50         |
| John          | 5             |  25         |

I'm struggling with how to get the total of the number row and use this as a value to calculate the rest.

EDIT: I'm looking to do this as a single query instead of two separate if possible.

like image 264
jonmrich Avatar asked May 28 '15 14:05

jonmrich


2 Answers

You just need to CROSS JOIN the SUM() of Number column:

SELECT Name, Number, Number * 100 / t.s AS `% of total`
FROM mytable
CROSS JOIN (SELECT SUM(Number) AS s FROM mytable) t

Demo Here

like image 110
Giorgos Betsos Avatar answered Oct 25 '22 21:10

Giorgos Betsos


If I were doing this, I would start by storing a variable that held the total, like this:

SET @total := (SELECT SUM(number) FROM myTable);

Once I had that variable, I could run a query that got the percentage for each row like this:

SELECT name, number, (number / @total) * 100 AS percentage
FROM myTable;

If you don't want to use a variable, you can just move that subquery into your select statement:

SELECT name, number, (number / (SELECT SUM(number) FROM myTable)) * 100 AS percentage
FROM myTable;

Here is an SQL Fiddle example with each approach.

like image 23
AdamMc331 Avatar answered Oct 25 '22 21:10

AdamMc331