最新客户捐款和金额

时间:2016-12-08 18:02:30

标签: sql-server tsql

我有两张桌子:

  1. Customer,其中Id列代表客户ID。
  2. CustomerDonation包含CustomerId(FK),AmountDatePayed
  3. 我希望让所有客户与他们最近的捐赠和捐赠金额一起。

    我在查询中收到重复值,因此我不会在此处粘贴。

4 个答案:

答案 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