;with CTE as (
select customerID, amount, product, date
from Sales
where Amount > 0 and CompletedSales = 'yes'
union
select CustomerID, amount, product, date
from SalesArchive
where Amount > 0 and CompletedSales = 'yes' and accountclosed = 'no'
), CTE2 as (
select *, row_number() over (partition by CustomerID order by [date] desc) rn from CTE
)
select * from CTE2
where rn = 1
|