我有两张桌子:
Customer
,其中Id
列代表客户ID。CustomerDonation
包含CustomerId
(FK),Amount
和DatePayed
我希望让所有客户与他们最近的捐赠和捐赠金额一起。
我在查询中收到重复值,因此我不会在此处粘贴。
答案 0 :(得分:3)
您也可以使用WITH TIES选项
Select Top 1 With Ties *
From YourTable
Order By Row_Number() over (Partition By CustomerId Order By DatePayed Desc)
答案 1 :(得分:1)
WITH
SortedDonation AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY DatePayed DESC) AS SeqID,
*
FROM
CustomerDonation
)
SELECT
*
FROM
Customer
LEFT JOIN
SortedDonation
ON SortedDonation.CustomerId = Customer.Id
AND SortedDonation.SeqId = 1
如果同一个客户可以使用相同的DatePayed
进行多次捐赠,那么这将随意挑选其中一个。
如果您向ORDER BY
添加其他字段,则可以确定地选择所需的字段。
或者,如果您希望所有人都使用DENSE_RANK()
而不是ROW_NUMBER()
答案 2 :(得分:0)
使用Row_Number()分析函数。
Select * from (
Select customerId,Amount,DatePayed, row_number() over (partition by CustomerId order by DatePayed desc) as rowN)
as tab where rowN = 1
答案 3 :(得分:0)
您只需要CustomerDonation
表格。如果您需要客户的其他信息,可以加入Customer
表。
WITH cte AS (
SELECT
CustomerId
, MAX(DatePayed) AS LastDate
FROM
CustomerDonation
)
SELECT
cd.CustomerId
, cd.Amount
, cd.DatePayed
FROM
CustomerDonation cd
JOIN cte ON cd.CustomerId = cte.CustomerId
AND cd.DatePayed = cte.LastDate