How about this?set nocount ondeclare @tb1 Table (id int, username varchar(10), productID int)declare @tb2 table (productID int, productname varchar(10))insert @tb1select 1, 'user1', 11 union allselect 2, 'user1', 11 union allselect 3, 'user1', 22 union allselect 4, 'user1', 22 union allselect 5, 'user1', 11 union allselect 6, 'user1', 33 union allselect 7, 'user2', 11 insert @tb2select 11, 'product11' union allselect 22, 'product22' union allselect 33, 'product33'select distinct username, productnamefrom @tb1 aJOIN @tb2 b ON a.productid = b.productidWhere a.ProductID IN ( Select top 2 productID from @tb1 where username = a.username group by productID order by count(*) desc )
Be One with the OptimizerTG