假设您想按 CLIENT_ID 获取 MIN(BOOKING_ID) 分组的 PROVIDER_ID,则以下内容应该有效:
SELECT
Client_ID,
Booking_ID,
Provider_ID
FROM (
SELECT
Client_ID,
Provider_ID,
Booking_ID,
ROW_NUMBER() OVER (PARTITION BY Client_ID ORDER BY Booking_ID) as RowNumber
FROM
Bookings
) OrderedTable
WHERE
OrderedTable.RowNumber = 1
它是如何工作的?ROW_NUMBER OVER (ORDER BY field)
如果结果集按特定字段排序,则为您提供行号。允许您按特定键(在本例中为 Client_ID)对表进行分区,该PARTITION BY field
键将为每个 Client_ID 重置 ROW_NUMBER(因此,如果 RowNumber = 1,则它是该特定客户端的第一个条目)
更多细节在这里:http: //msdn.microsoft.com/en-us/library/ms186734.aspx
使用 WITH 语法:
WITH OrderedTable AS
(
SELECT
Client_ID,
Provider_ID,
Booking_ID,
ROW_NUMBER() OVER (PARTITION BY Client_ID ORDER BY Booking_ID) as RowNumber
FROM
Bookings
)
SELECT
Client_ID,
Provider_ID,
Booking_ID
FROM
OrderedTable
WHERE
RowNumber = 1