gpt4 book ai didi

MySQL - 选择年总和的最大值

转载 作者:行者123 更新时间:2023-11-29 02:10:12 24 4
gpt4 key购买 nike

我有这样的表:

  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

最佳答案

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

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

请注意,如果您有两行匹配最大值,则查询将返回两行

关于MySQL - 选择年总和的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54731584/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com