Hi,
As per my understanding of your question, I have prepared below sql query steps.
Step #1. Get your data into "TmpResult" column in new table2 using ROW_NUMBER(), partition by and order by from table1.
Step #2. Get your expected result using table2 by formatting "TmpResult" column.
Please re-order column names in order by query as per your requirement.
I hope this query may help you get close result which you want.
Thank you.
-- Get data in second table using ROW_NUMBER, partition by and order by
select ID,INV,Dates,(ROW_NUMBER() OVER (partition by ID order by ID,INV,Dates) - 1) TmpResult into table2 from table1 order by ID,INV,Dates
select * from table2
select ID,INV,Dates,TmpResult,
(case when TmpResult = 0 then NULL
else
(case when TmpResult = 1 then '1st'
when TmpResult = 2 then '2nd'
when TmpResult = 3 then '3rd'
else convert(varchar(5),TmpResult)+'th'
end)
end) ExpectedResult
from table2