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

后端 未结 3 1363
眼角桃花
眼角桃花 2020-12-10 04:28

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 Nam

相关标签:
3条回答
  • 2020-12-10 04:35

    You can get it with a subselect:

    SELECT Name, Number, Number * 100 / (select sum(Number) FROM MYTABLE) AS '% of total'
    FROM mytable
    
    0 讨论(0)
  • 2020-12-10 04:58

    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

    0 讨论(0)
  • 2020-12-10 05:02

    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.

    0 讨论(0)
提交回复
热议问题