0

我在 SQL Server 中有一个名为 [Donations] 的表,其中包含各种人的捐款。

它的字段是:

FirstName,LastName,FullName,Description --VARCHARs
DateOrdered, --DATE
Donation     --MONEY

我希望返回表中的所有字段,但我只想要每个人最大的捐赠记录,而不是他们所有的捐赠。

假设该表包含 8 条记录,John Doe 有 5 条捐赠记录,而 Jane Doe 有 3 条。我希望编写一个查询,它将给出 John 的最大捐赠记录和 Jane 的捐赠记录。最大的捐赠。

我怎样才能用 SQL 写这个?

非常感谢您的帮助。

4

3 回答 3

3
select
  *
from
  donations d
where
  donation=(select max(donation) from donations where fullname=d.fullname group by fullname)

这假设 fullname 是您在此表上的 PK。

于 2012-06-30T01:56:53.723 回答
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
于 2012-06-30T08:19:27.753 回答
0

尝试这个:

select d1.*,(select max(d2.donation) where d2.fullname=d1.fullname group d2.fullname) from donation d1;
于 2012-06-30T09:18:30.273 回答