I have three tables full of item observations, each with say the following columns: Table2015: ItemName, ItemCount Table2014: ItemName, ItemCount Table2013: ItemName, ItemCount
and I'd like to get the 3 highest Counts for each ItemName from Table2015 with a special column that in the report that flags the row if the highest Count for that ItemName in Table2015 is greater than the highest Count for it in Table2014 and Table2013.
I have the following to get the high counts from Table2015, I'm not sure how to proceed to get what I need. Should I use another CTE with the other tables and join it in the final select somehow?
with counts as (
select e.ItemName, e.ItemCount, row_number() over (partition by e.ItemName order by cast(e.ItemCount as int) desc) as rk
from Table2015 e where e.ItemCount <> 'X')
select s.*,
from counts s
where s.rk<4
order by s.ItemName,s.rk;