简体   繁体   中英

MySQL - select max value with of sum over year

I have table like:

  v   | day | month | year
  1      1     1      1950
  2      2     1      1950
  3      3     1      1950
  1      1     2      1950
  1      1     2      1951
  2      1     2      1952

I have used this query to select MINs

SELECT SUM(v) AS sum_val, year, month
FROM `d`
GROUP BY year, month

This will result in

sum_val | year | month  
  6       1950     1
  1       1950     2
  1       1951     2 
  2       1952     2

How can I select max of sum_val with assigned year grouped by month? I have tried

SELECT (MAX(f.sum_val)) AS max_sum, f.year, f.month
FROM (
    SELECT SUM(v) AS sum_val, year, month
    FROM `d`
    GROUP BY year, month
) AS f
GROUP BY month

but this incorrectly assign year to value

max_sum | year | month  
   6      1950    1
   2      1950    2   <--- should be 1952

SqlFiddle: http://sqlfiddle.com/#!9/ab23b4/6/0

You could use some subquery baset on sum_val in join

select t2.sum_val, t2.year, t2.month 
from (
    SELECT SUM(v) AS sum_val, year, month
    FROM `d`
    GROUP BY year, month
) t2 
INNER JOIN (
    select max(sum_val) max_val, year
    from (
        SELECT SUM(v) AS sum_val, year, month
        FROM `d`
        GROUP BY year, month
    )  t  
    group by year 
) t3  on t3.max_val = t2.sum_val    and t3.year  = t2.year

NB in ths way if you have two rows that match max val the query return two rows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM