MySQL查找一年中每个月的SUM的最大值[MYSQL]

时间:2017-10-01 22:01:16

标签: mysql sql

目前我能够获得一年中每个月最高金额的金额。但我想做的是,能够获得每年最高价值的月份的总和。

SELECT year(paymentDate), month(paymentDate) , SUM(amount)
FROM classicmodels.payments
GROUP BY year(paymentDate), month(paymentDate) 
ORDER BY SUM(amount) DESC;

这按照降序排列最高的SUM(金额),但我只想获得每年最高的月份。我的数据库只有3年。

Here's what happening on mysql workbench

1 个答案:

答案 0 :(得分:0)

一种方法使用having子句:

SELECT year(p.paymentDate), month(p.paymentDate), SUM(p.amount)
FROM classicmodels.payments p
GROUP BY year(p.paymentDate), month(p.paymentDate) 
HAVING SUM(p.amount) = (SELECT SUM(p2.amount)
                        FROM classicmodels.payments p2
                        WHERE year(p2.paymentDate) = year(p.paymentDate)
                        GROUP BY month(p2.paymentDate)
                        ORDER BY SUM(p2.amount) DESC
                        LIMIT 1
                       )
ORDER BY SUM(amount) DESC;