MySQL - How to SELECT based on value of another SELECT

前端 未结 3 1360
庸人自扰
庸人自扰 2021-01-30 06:22

I have a table that looks something like this:

Name    Year   Value
 A      2000     5
 A      2001     3
 A      2002     7
 A      2003     1
 B      2000              


        
3条回答
  •  执笔经年
    2021-01-30 07:22

    You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

    SELECT Name,
           SUM(Value) AS "SUM(VALUE)",
           SUM(Value) / totals.total AS "% of Total"
    FROM   table1,
           (
               SELECT Name,
                      SUM(Value) AS total
               FROM   table1
               GROUP BY Name
           ) AS totals
    WHERE  table1.Name = totals.Name
    AND    Year BETWEEN 2000 AND 2001
    GROUP BY Name;
    

    Note that the subquery does not have the WHERE clause filtering the years.

提交回复
热议问题