0

There may be a more elegant way of doing it inside the CTE, but here's my solution.
WITH cte (rowNo, itemNo, dueDate, amountDue) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY [Due Date]) rowNo,
[Item No], [Due Date], [Amount Due]
FROM loans
)
SELECT a.itemNo, a.dueDate,
CASE WHEN c.dueDate ...