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

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


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.

Tags:

Mysql