[英]MySQL Finding the MAX of the SUM of each month of the year [MYSQL]
Currently i am able to get the sum for the highest amount for each month of the year.目前,我能够获得一年中每个月最高金额的总和。 But what i want to do, is to be able to get the SUM of the month that has the highest value in amount for each year.但是我想要做的是能够获得每年金额最高的月份的总和。
SELECT year(paymentDate), month(paymentDate) , SUM(amount)
FROM classicmodels.payments
GROUP BY year(paymentDate), month(paymentDate)
ORDER BY SUM(amount) DESC;
This orders the highest SUM(amount) in descending order but i only want to get the highest month for each year.这按降序排列最高的 SUM(amount),但我只想获得每年最高的月份。 there are only 3 years in my database.我的数据库中只有 3 年。
One method uses a having
clause:一种方法使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.