简体   繁体   中英

SELECT TOP(N) Rows For Each GROUP

Here is my query thus far:

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

What I want is to get 2 rows for each star rating: 2 of rating 3, 2 of rating 4 and 2 of rating 5. How can I do this? I have come up with the above after doing some research online already, but I am obviously not fully understanding hwo to implement it, because it is not working... I am getting 6 rows of star rating 3

Use ROW_NUMBER function - for example,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM