我在SQL Server中有一个名为[Donations]的表,其中包含由不同人员提供的捐赠。
其字段为:
FirstName,LastName,FullName,Description --VARCHARs
DateOrdered, --DATE
Donation --MONEY
我希望退回表格中的所有字段,但我只想要每个人最大的捐赠记录,而不是所有捐款。
假设该表包含8条记录,John Doe有5条捐赠记录,Jane Doe有3条记录。 我希望写一个查询,这将为我提供约翰的捐赠记录,这是他捐赠的最大捐款,以及Jane捐赠记录,这是她最大的捐款。
如何在SQL中编写?
非常感谢您的帮助。
答案 0 :(得分:3)
select
*
from
donations d
where
donation=(select max(donation) from donations where fullname=d.fullname group by fullname)
这假设fullname是你在这张桌子上的PK。
答案 1 :(得分:1)
以下是使用排名函数的示例:
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
答案 2 :(得分:0)
试试这个:
select d1.*,(select max(d2.donation) where d2.fullname=d1.fullname group d2.fullname) from donation d1;