Select only last value of date?

巧了我就是萌 提交于 2019-12-11 19:08:45

问题


I have a SELECT, that returns me something similar to this result (I've simplified it, because the original SELECT is rather complex):

| UserFK    | aDate             | aValue    |
---------------------------------------------
| 1000      | 03.12.2012 10:00  | 123       |
| 1000      | 03.12.2012 11:00  | 456       | <--
| 1001      | 03.12.2012 09:00  | 111       | <--
| 1002      | 03.12.2012 09:00  | 222       |
| 1002      | 03.12.2012 10:00  | 333       | <--
| 1003      | 03.12.2012 09:00  | 123       | 
| 1003      | 02.12.2012 09:00  | 123       |
| 1003      | 03.12.2012 10:00  | 455       | <--
| 1004      | 03.12.2012 11:00  | 123       | <--

Now I don't want any duplicate UserFK, I only want the last (by aDate) UserFK and it's value. I've marked the ones that I actually want.

Is there a simple way to do it?


回答1:


You can use a CTE with a ROW_NUMBER like this:

WITH CTE AS
(
   SELECT UserFK, aDate, aValue,
     RN = ROW_NUMBER() OVER (PARTITION BY UserFK ORDER BY aDate DESC)
   FROM dbo.TableName
)
SELECT UserFK, aDate, aValue
FROM CTE
WHERE RN = 1


来源:https://stackoverflow.com/questions/13679701/select-only-last-value-of-date

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