I have two tables from which I’m trying to run a query to return the maximum (or top) transaction for each person. I should note that I cannot change the table structure. Rather, I can only pull data.
People
+-----------+ | id | name | +-----------+ | 42 | Bob | | 65 | Ted | | 99 | Stu | +-----------+
Transactions (there is no primary key)
+---------------------------------+ | person | amount | date | +---------------------------------+ | 42 | 3 | 9/14/2030 | | 42 | 4 | 7/02/2015 | | 42 | *NULL* | 2/04/2020 | | 65 | 7 | 1/03/2010 | | 65 | 7 | 5/20/2020 | +---------------------------------+
Ultimately, for each person I want to return the highest amount. If that doesn’t work then I’d like to look at the date and return the most recent date.
So, I’d like my query to return:
+----------------------------------------+ | person_id | name | amount | date | +----------------------------------------+ | 42 | Bob | 4 | 7/02/2015 | (<- highest amount) | 65 | Ted | 7 | 5/20/2020 | (<- most recent date) | 99 | Stu | *NULL* | *NULL* | (<- no records in Transactions table) +----------------------------------------+
SELECT People.id, name, amount, date
FROM People
LEFT JOIN (
SELECT TOP 1 person_id
FROM Transactions
WHERE person_id = People.id
ORDER BY amount DESC, date ASC
)
ON People.id = person_id
I can’t figure out what I am doing wrong, but I know it’s wrong. Any help would be much appreciated.
You are almost there but since there are duplicate Id in the Transaction table ,so you need to remove those by using Row_number() function
Try this :
The result is in Sql Fiddle
Edit: Row_number() from MSDN
Partition is used to group the result set and Over by clause is used