The immediate problem is that you have asked a select
to output rows each containing a value for sellerId
, Country
and three values for ItemID
.
The subquery is also not correlated with the outer query, i.e. you have a second reference to the Sellers
table, but have done nothing to match up values with the outer query.
Assuming that you actually want the top 3 items for each of up to 10 countries, this should be close:
-- Sample data.
declare @Sellers as Table ( SellerId Int, Country VarChar(16) );
insert into @Sellers ( SellerId, Country ) values
( 1, 'Canada' ), ( 2, 'Italy' ), ( 3, 'Elbonia' ), ( 4, 'Maldives' ), ( 5, 'Fiji' ),
( 6, 'Ecuador' ), ( 7, 'Chile' ), ( 8, 'Mexico' ), ( 9, 'Palau' ), ( 10, 'Yap' ),
( 11, 'Saba' );
declare @Items as Table ( ItemId Int, UserId Int, CreatedDate Date );
insert into @Items ( ItemId, UserId, CreatedDate ) values
( 1, 3, '20150308' ), ( 2, 3, '20150619' ), ( 3, 3, '20120908' ), ( 4, 3, '20140228' ),
( 2, 9, '20150308' ), ( 3, 9, '20150619' ), ( 4, 9, '20120908' ), ( 5, 9, '20140228' ),
( 3, 6, '20150308' ), ( 4, 6, '20150619' ), ( 4, 6, '20120908' ), ( 6, 6, '20140228' );
select * from @Sellers;
select * from @Items;
-- Show the intermediate results.
with AllSellersAndItems as
( select S.SellerId, S.Country, I.ItemId,
Row_Number() over ( partition by S.SellerId order by I.CreatedDate ) as ItemSequence,
Dense_Rank() over ( order by Country ) as SellerSequence
from @Sellers as S inner join
@Items as I on I.UserId = S.SellerId )
select * from AllSellersAndItems;
-- The real query.
with AllSellersAndItems as
( select S.SellerId, S.Country, I.ItemId,
Row_Number() over ( partition by S.SellerId order by I.CreatedDate ) as ItemSequence,
Dense_Rank() over ( order by Country ) as SellerSequence
from @Sellers as S inner join
@Items as I on I.UserId = S.SellerId )
select SellerId, Country, ItemId, SellerSequence, ItemSequence
from AllSellersAndItems
where SellerSequence <= 10 and ItemSequence <= 3
order by Country desc