MySQL - 选择总和超过年份的最大值

问题描述 投票:2回答:1

我有这样的表:

  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

我使用此查询来选择MIN

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

这将导致

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

如何选择按月分组的年份sum_val的最大值?我试过了

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

但这不正确地指定年份值

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

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

mysql group-by max
1个回答
2
投票

您可以在join中使用基于sum_val的子查询

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

注意,如果你有两行匹配最大值,查询返回两行

© www.soinside.com 2019 - 2024. All rights reserved.