简体   繁体   中英

SQL, get the highest payment month of each year

I currently have this that shows me the total of how much the amount is per month. What i want to get from this, is to show the month that made the highest amount per each year.

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

Here is the table that i want to only show the month that got the highest amount for each year

img结果

SUM(Amount)一个列别名, ORDER BY <that alias> DESC并将TOP(1)添加到SELECT

You can use ROW_NUMBER for this:

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

Note: In case of ties the query return an arbitrary month. To return all months having the biggest amount use RANK instead of ROW_NUMBER .

Using ROW_NUMBER() you can assign sequence number for each records based on your criteria, and select the record with sequence 1. Sample below;

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

There are lot of other ways to achieve the same.

and WHERE D.ROW_ORDER = n --you will return the n'th highest for each year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM