从一个到多个表获取Max(id)

时间:2015-01-19 19:39:51

标签: sql-server greatest-n-per-group

我知道这个问题曾多次被问到,但我一直在努力尝试而没有成功

我在两个表之间有one to many个关系,而另一些表inner-joinsSELECT ShopOffer.OfferID, ShopOffer.OfferMessage, Shop.ID, Shop.Name, Shop.Phone, [User].Name, [User].UserID, ShopOfferStatus.Name AS StatusName, BlockedShopInUser.IsBlocked FROM ShopOffer INNER JOIN ShopOfferStatus ON ShopOffer.ShopOfferStatusID = ShopOfferStatus.ShopOfferStatusID INNER JOIN Shop ON ShopOffer.ShopID = Shop.ShopID INNER JOIN UserRequest ON ShopOffer.UserRequestID = UserRequest.UserRequestID INNER JOIN [User] ON UserRequest.UserID = [User].UserID INNER JOIN BlockedShopInUser ON Shop.ShopID = BlockedShopInUser.ShopID AND [User].UserID = BlockedShopInUser.UserID 来获取更多数据。

这是我的问题:

{{1}}

每家商店都可以创造许多优惠。在那个查询中,我想获得每个商店的最后一个报价。

感谢。

2 个答案:

答案 0 :(得分:2)

这是一种方式:

;WITH LastShopOffer AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY ShopID ORDER BY OfferID DESC)
    FROM ShopOffer
)
SELECT     
    SO.OfferID, 
    SO.OfferMessage,     
    S.ID,                             
    S.Name,           
    S.Phone, 
    U.Name,            
    U.UserID, 
    SOS.Name AS StatusName,     
    B.IsBlocked
FROM (  SELECT * 
        FROM LastShopOffer
        WHERE RN = 1) SO
INNER JOIN ShopOfferStatus SOS 
    ON SO.ShopOfferStatusID = SOS.ShopOfferStatusID 
INNER JOIN Shop S
    ON SO.ShopID = S.ShopID 
INNER JOIN UserRequest UR
    ON SO.UserRequestID = UR.UserRequestID 
INNER JOIN [User] U 
    ON UR.UserID = U.UserID 
INNER JOIN BlockedShopInUser B
    ON S.ShopID = B.ShopID 
    AND U.UserID = B.UserID;

答案 1 :(得分:1)

我认为您必须从Shop开始,然后对来自CROSS APPLY的{​​{1}}记录执行TOP 1

ShopOffer