1 1 ( "9" ) "2" 2 ( "7" "8" ), :
select top (1) with ties t.*
from (select cte.*,
row_number() over (partition by stdid order by date) as seqnum
from cte
where student = @student
) t
order by (dt - seqnum) desc;
? -, . dt "dt".
. .
:
These are reasonable assumptions based on the question and the data in the question. There are fairly simple alternatives to handle other situations.
Finally, let me note that if your data is more like an image than a CTE, an easy way to convert it is:
select top (1) with ties t.*
from (select cte.*,
row_number() over (partition by stdid order by date) as seqnum
from t cross apply
(values (t.[1]), (t.[2]), . . . ) v(dt)
where student = @student and v.dt = 'yes'
) t
order by (dt - seqnum) desc;
source
share