Nesting the CTE doesn't work either:
SELECT *
FROM (
SELECT *, ROW=ROW_NUMBER() OVER (
PARTITION BY facility_identifier, stay_number, episode_sequence_number
ORDER BY replica_valid_from_date DESC
)
FROM (
SELECT *
FROM [dbo].[EPISODE]
WHERE (
(? <= [replica_valid_to_date] AND [replica_valid_to_date] < ?)
OR
(? <= [replica_valid_from_date] AND [replica_valid_from_date] < ?)
)
) x
) x
WHERE ROW=1
The error message says put the entire block of code in a variable - also doesn't work.