为一系列活跃的广告商店选择每个商店随机排名前3的商品

时间:2010-04-28 06:33:40

标签: sql sql-server sql-server-2005 subquery

我正在尝试显示一个商店列表,每个商店都有3个随机商品,如果他们有3个或更多商品,那就是积极做广告。我有3个桌子:一个用于商店 - “商店”,一个用于列表 - “列表”,一个用于跟踪活跃的广告商 - “AdShops”。

使用下面的语句,返回的列表是随机的,但我没有得到每个商店返回的3个列表(行)。

SELECT AdShops.ID, Shops.url, Shops.image_url, Shops.user_name AS shop_name,
       Shops.title, L.listing_id AS listing_id, L.title AS listing_title,
       L.price as price, L.image_url AS listing_image_url, L.url AS listing_url
FROM   AdShops INNER JOIN
       Shops ON AdShops.user_id = Shops.user_id INNER JOIN
       Listings AS L ON Shops.user_id = L.user_id
WHERE  (Shops.is_vacation = 0 AND Shops.listing_count > 2 AND 
        L.listing_id IN
            (SELECT TOP 3 L2.listing_id
             FROM   Listings AS L2
             WHERE  L2.listing_id IN 
                 (SELECT TOP 100 PERCENT L3.listing_id
                  FROM   Listings AS L3
                  WHERE  (L3.user_id = L.user_id)
                 )
             ORDER BY NEWID()
            )
       )
ORDER BY Shops.shop_name

我很难过。任何人对如何解决它有什么想法?

理想的解决方案是每个商店一个记录,其中3个列表(和相关数据)是列而不是行 - 这可能吗?

2 个答案:

答案 0 :(得分:1)

如果我没有弄错,下面的查询应该会给你每个user_id至少有3个随机的listing_id。

SELECT  user_id
        , listing_id
FROM    (
          SELECT  l.user_id 
                  , l.listing_id
                  , RowNumber = ROW_NUMBER() OVER (PARTITION BY l.user_id ORDER BY NEWID())
          FROM    Listings l
                  INNER JOIN (
                    SELECT  user_id
                    FROM    Listings
                    GROUP BY
                            user_id
                    HAVING  COUNT(*) >= 3
                  ) cnt ON cnt.user_id = l.user_id  
        ) l 
WHERE   l.RowNumber <= 3

答案 1 :(得分:1)

感谢列文解决问题的关键。完整的解决方案如下:

SELECT AdShops.ID, Shops.url, Shops.image_url, 
       Shops.user_name AS shop_name, Shops.title, L.listing_id AS listing_id, 
       L.title AS listing_title, L.price as price,
       L.image_url AS listing_image_url, L.url AS listing_url
FROM   AdShops INNER JOIN
       Shops ON AdShops.user_id = Shops.user_id INNER JOIN
       Listings AS L ON Shops.user_id = L.user_id
WHERE  (Shops.is_vacation = 0 AND Shops.listing_count > 2 AND 
        L.listing_id IN
            (SELECT listing_id
             FROM    
                 (SELECT l2.user_id , l2.listing_id, RowNumber = ROW_NUMBER() 
                  OVER   (PARTITION BY l2.user_id ORDER BY NEWID())
                  FROM   Listings l2 INNER JOIN
                      (SELECT   user_id
                       FROM     Listings
                       GROUP BY user_id
                       HAVING   COUNT(*) >= 3
                      ) cnt ON cnt.user_id = l2.user_id  
                 ) l2 
             WHERE l2.RowNumber <= 3 and L2.user_id = L.user_id
            )
       )
ORDER BY Shops.shop_name

享受!