我目前有这个显示了每月金额的总和。我想从中获得的是显示每年最高金额的月份。
SELECT year(paymentDate), month(paymentDate) , SUM(amount)
FROM classicmodels.payments
GROUP BY year(paymentDate), month(paymentDate)
ORDER BY paymentDate ASC;
以下表格我只想显示每年获得最高金额的月份
答案 0 :(得分:0)
为SUM(Amount)
添加列别名ORDER BY <that alias> DESC
并将TOP(1)
添加到SELECT
答案 1 :(得分:0)
您可以使用ROW_NUMBER
:
SELECT y, m, amount
FROM (
SELECT YEAR(paymentDate) AS y, MONTH(paymentDate) AS m,
amount,
ROW_NUMBER() OVER (PARTITION BY YEAR(paymentDate) ORDER BY amount DESC) AS rn
FROM classicmodels.payments) AS t
WHERE t.rn = 1
注意:如果是绑定,查询将返回任意月份。要返回金额最大的所有月份,请使用RANK
而不是ROW_NUMBER
。
答案 2 :(得分:0)
使用ROW_NUMBER()
您可以根据您的条件为每条记录分配序列号,并选择序列为1的记录。
以下示例;
SELECT *
FROM (
SELECT year(paymentDate) year_val, month(paymentDate) month_val, SUM(amount) amt_val,
ROW_NUMBER() OVER(PARTITION BY year(paymentDate) ORDER BY SUM(amount) DESC) AS ROW_ORDER
FROM classicmodels.payments
GROUP BY year(paymentDate), month(paymentDate)
) AS D
WHERE D.ROW_ORDER = 1
还有很多其他方法可以实现同样的目标。
和WHERE D.ROW_ORDER = n
- 你将每年返回第n位。