Select only last value of date?

2019-08-30 09:03发布

问题:

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