简体   繁体   中英

SQL - Pull distinct row based on max value

I am trying to pull the most recent sale amount for each salesperson. The salespeople have made a sale on multiple days, I only want the most recent one.

My attempt below:

SELECT salesperson, amount
FROM table
WHERE date = (SELECT MAX(date) FROM table);

Use correlated subquery:

SELECT t.salesperson, t.amount
FROM table t
WHERE t.date = (SELECT MAX(t1.date) 
                FROM table t1 
                WHERE t1.salesperson = t.salesperson -- for each salesperson
               );

If you are using PostgreSQL, you can take advantage of DISTINCT ON :

SELECT DISTINCT ON (salesperson) salesperson, amount
FROM table t
ORDER BY salesperson, date DESC

This will return only one row for each salesperson. The ORDER BY clause says to return the one with the largest date for that salesperson.

Unfortunately, DISTINCT ON is not supported by other databases.

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