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

时间:2019-02-17 08:53:37

标签: mysql group-by max

我的桌子像:

  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

我已使用此查询来选择MINs

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

1 个答案:

答案 0 :(得分:2)

您可以在join的sum_val上使用一些子查询

df_test = pd.DataFrame(data = np.arange(0,100))
df_test_ewma = df_test.ewm(span=2).mean()

以这种方式注意,如果您有两行与max val相匹配,查询将返回两行