This does not directly answer the question, but I am trying to explain why what you are trying does not work as you expect.
Your problem is caused by PARTITION . If you remove the unique columns from your PARTITION clause, you will be left with afdelingscode . So your PARTITION groups the data like this:
RD8-GH Endo RD8-GH MAU RD8-GH MAU RD8-GH Ward 08 RD8-GH Ward 08 RD8-GH Ward 08
The ORDER BY determines the order in your PARTITION , so when you delete the non-historical columns again, you get the ORDER BY OntslagDatumTijd , which produces this where it is ordered by the date column, notes that the sections are still separated by afdelingscode :
afdelingscode OntslagDatumTijd RD8-GH Endo 2014-09-09 09:06:00.000 RD8-GH MAU 2014-09-01 14:50:00.000 RD8-GH MAU 2014-09-02 19:32:00.000 RD8-GH Ward 08 2014-09-03 17:12:00.000 RD8-GH Ward 08 2014-09-17 17:00:00.000 RD8-GH Ward 08 2014-10-01 17:15:00.000
Then ranking is applied to these sections. The result of this will be:
rnk afdelingscode OntslagDatumTijd 1 RD8-GH Endo 2014-09-09 09:06:00.000 1 RD8-GH MAU 2014-09-01 14:50:00.000 2 RD8-GH MAU 2014-09-02 19:32:00.000 1 RD8-GH Ward 08 2014-09-03 17:12:00.000 2 RD8-GH Ward 08 2014-09-17 17:00:00.000 3 RD8-GH Ward 08 2014-10-01 17:15:00.000
Thus, it is graded according to how you indicated, the problem in your release is that at the end of your selection (unhistorical column removal), the OntslagDatumTijd date column is ordered, which gives you:
rnk afdelingscode OntslagDatumTijd 1 RD8-GH MAU 2014-09-01 14:50:00.000 2 RD8-GH MAU 2014-09-02 19:32:00.000 1 RD8-GH Ward 08 2014-09-03 17:12:00.000 1 RD8-GH Endo 2014-09-09 09:06:00.000 2 RD8-GH Ward 08 2014-09-17 17:00:00.000 3 RD8-GH Ward 08 2014-10-01 17:15:00.000
I will continue to look at this if the other answer you sent does not meet your requirements.
Reference:
OVER offer
SECTION . Partitioning the query result set into sections. The window function is applied to each section separately and the calculation is restarted for each section.
ORDER BY clause Defines the logical order of the rows in each section of the result set. That is, it determines the logical order in which the calculation of the window function is performed.
Here's a potential solution that may have performance issues with the size of the data you are using, but you can check it out:
You will MAXRECURSION into the MAXRECURSION limit for a larger dataset for which you need to change the limit using the following after the final SELECT :
SELECT * FROM cte OPTION (MAXRECURSION 0)
Setting this value to 0 will not impose any restrictions; you can set this number to the size of your data set, if you know it.