Mukesh
Mukesh

Reputation: 807

Use Partition in SQL

I have a problem with a query. Here is the query.

SELECT UserID, MAX(UserName) as UserName, MAX(TransactionTime) as TransactionTime,         MAX(LastAction) as LastAction 
FROM UserActivities 
WHERE OrganizationID = 26465
GROUP BY UserID

There are so many records for particular user at different TransactionTime. I want to take LastAction along with other records. How can I do it? Is SQL partition will work here?

Upvotes: 1

Views: 2975

Answers (1)

Andreas Ågren
Andreas Ågren

Reputation: 3929

A ranking function is probably what you are looking for:

SELECT *
FROM (
   SELECT UserID, UserName, LastAction, row_number() over(partition by UserId order by TransactionTime desc) RowNo
   FROM UserActivities 
   WHERE OrganizationID = 26465
) t
where t.RowNo = 1

Upvotes: 3

Related Questions