SELECT TOP(N)每个组的行

时间:2011-10-19 04:14:19

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

到目前为止,这是我的查询:

SELECT [Id], [HotelName], [StarRating], [Description], [CheckinDate], [CheckoutDate], [Price], [ImageUrl]
FROM
(
    SELECT TOP (6) [Id], [HotelName], [StarRating], [Description], [CheckinDate], [CheckoutDate], [Price], [ImageUrl], RANK() OVER(PARTITION BY [StarRating] ORDER BY [StarRating]) AS Num
    FROM [dbo].[Hotel]
    WHERE [CityId] = @CityId 
    AND CheckinDate > GETDATE()
    AND [StarRating] IN (3, 4, 5)
) X
WHERE Num <= 2

我想要的是为每个星级评分获得2行:评级3中的2,评级4中的2和评级5中的2.我该怎么做?我已经在网上进行了一些研究后得出了上述内容,但我显然还没有完全理解hwo来实现它,因为它不起作用......我得到了6行星级评分3

1 个答案:

答案 0 :(得分:8)

使用ROW_NUMBER函数 - 例如,

WITH X 
AS
(
    SELECT 
       [Id], [HotelName], [StarRating], [Description], 
       [CheckinDate], [CheckoutDate], [Price], [ImageUrl], 
       ROW_NUMBER() OVER(PARTITION BY [StarRating] ORDER BY [Id]) AS Num
    FROM 
       [dbo].[Hotel]
    WHERE 
       [CityId] = @CityId 
         AND CheckinDate > GETDATE()
         AND [StarRating] IN (3, 4, 5)
) 
SELECT 
   [Id], [HotelName], [StarRating], [Description], 
   [CheckinDate], [CheckoutDate], [Price], [ImageUrl]
FROM 
   X
WHERE 
   Num <= 2