Use Partition in SQL

蹲街弑〆低调 提交于 2019-12-02 19:45:47

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/7022743/use-partition-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!