gpt4 book ai didi

sql - 为每个组选择前 (N) 行

转载 作者:行者123 更新时间:2023-12-01 13:51:41 25 4
gpt4 key购买 nike

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

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 行。我该怎么做?我已经在网上做了一些研究之后想出了以上内容,但我显然不完全理解如何实现它,因为它不起作用......我得到 6 行星级 3

最佳答案

使用 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

关于sql - 为每个组选择前 (N) 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7816457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com