这是使用排名函数的示例:
DECLARE @Donations TABLE (FirstName VARCHAR(128),LastName VARCHAR(128),
FullName VARCHAR(256),Description VARCHAR(1024),
DateOrdered DATETIME, Donation DECIMAL)
INSERT @Donations VALUES
('John', 'Doe', 'John Doe', '', '20120605', 125),
('John', 'Doe', 'John Doe', '', '20120603', 12.34),
('John', 'Doe', 'John Doe', '', '20120602', 13.59),
('John', 'Doe', 'John Doe', '', '20120609', 125),
('John', 'Doe', 'John Doe', '', '20120601', 15),
('Jane', 'Doe', 'Jane Doe', '', '20120612', 155),
('Jane', 'Doe', 'Jane Doe', '', '20120613', 152),
('Jane', 'Doe', 'Jane Doe', '', '20120612', 155)
-- Return maximum donations including duplicate donations
-- on different and same dates
;WITH a AS
(
SELECT *,
DENSE_RANK() OVER (PARTITION BY FullName
ORDER BY Donation DESC) DenseRank
FROM @Donations
)
SELECT *
FROM a
WHERE DenseRank = 1
ORDER BY Donation DESC, DateOrdered DESC
-- Return maximum donations including duplicate donations on same dates,
-- excluding duplicate donations on different dates
;WITH a AS
(
SELECT *,
DENSE_RANK() OVER (PARTITION BY FullName
ORDER BY Donation DESC, DateOrdered DESC) DenseRank
FROM @Donations
)
SELECT *
FROM a
WHERE DenseRank = 1
ORDER BY Donation DESC, DateOrdered DESC
-- Return maximum donations excluding duplicate donations
-- on same and different dates
;WITH a AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY FullName
ORDER BY Donation DESC, DateOrdered DESC) RowNum
FROM @Donations
)
SELECT *
FROM a
WHERE RowNum = 1
ORDER BY Donation DESC, DateOrdered DESC