MySQL - How to SELECT based on value of another SELECT

前端 未结 3 1365
庸人自扰
庸人自扰 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:02
    SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
    FROM tbl t
    INNER JOIN 
    (SELECT name, SUM(value) as summary
    FROM tbl
    WHERE year BETWEEN 2000 AND 2001
    GROUP BY name) x ON x.name = t.name
    GROUP BY x.name, x.summary
    
    0 讨论(0)
  • 2021-01-30 07:13

    If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

    http://beginner-sql-tutorial.com/sql-subquery.htm

    For example, (from the link above):

    1. You want the first and last names from table "student_details" ...

    2. But you only want this information for those students in "science" class:

      SELECT id, first_name
      FROM student_details
      WHERE first_name IN (SELECT first_name
      FROM student_details
      WHERE subject= 'Science'); 
      

    Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

    IMHO...

    0 讨论(0)
  • 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.

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