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