1

不幸的是,SQL 对我来说并不容易。我有两张桌子,一张Loan桌子和一张LoanPayments桌子。

贷款支付表:

ID(主键)、LoanID(匹配贷款表上的 ID)、PaymentDate、Amount 等。

我需要一个 sql 语句,它可以给我每个月输入的最后一笔付款(如果有的话)。我目前的陈述没有给我结果。还有一个问题是有时会在那个月的最大日期出现平局,所以我也需要能够处理这个问题(我的想法是在平局的情况下选择最大的 ID)。

这是我到目前为止所拥有的(我知道这是错误的,但我不知道为什么。):

SELECT lp.ID, lp.LoanID, lp.PaymentDate 
FROM LoanPayments lp 
WHERE lp.PaymentDate in (
                          SELECT DISTINCT MAX(PaymentDate) as PaymentDate 
                          FROM LoanPayments 
                          WHERE IsDeleted = 0
                          AND ReturnDate is null 
                          GROUP BY YEAR(PaymentDate), Month(PaymentDate)
                        ) 
AND CAST(PaymentDate as date) >= CAST(DATEADD(mm, -24, GETDATE()) as date)

最后一部分只是过滤它,所以我只能得到最近 24 个月的付款。感谢您的帮助并花时间帮助我解决这个问题。

4

2 回答 2

10

您可以在这里使用 ROW_NUMBER() 函数:

SELECT *
FROM (SELECT lp.ID, lp.LoanID, lp.PaymentDate
          , ROW_NUMBER() OVER (PARTITION BY YEAR(PaymentDate), Month(PaymentDate) ORDER BY PaymentDate DESC) 'RowRank'
      FROM LoanPayments lp 
     )sub
WHERE RowRank = 1

这只是每个月最近的 PaymentDate,如果您希望通过 LoanID 获得它,您可以将 LoanID 添加到PARTITION BY列表中。如果您对保留关系感兴趣,可以使用RANK()而不是ROW_NUMBER()

于 2013-07-02T22:37:59.173 回答
0

第 1 步:使用窗口函数添加一个按月保存最大 PaymentDate 的列

SELECT
  ID,
  LoanID,
  PaymentDate,
  MAX(PaymentDate) OVER(PARTITION BY YEAR(PaymentDate), MONTH(PaymentDate)) AS MaxPaymentDate,
  ROW_NUMBER() OVER(PARTITION BY PaymentDate ORDER BY ID) AS TieBreaker
FROM LoanPayments 
WHERE IsDeleted = 0
AND ReturnDate is null

第 2 步:将这些结果过滤到您想要的行

SELECT ID,LoanID,PaymentDate
FROM (
  SELECT
    ID,
    LoanID,
    PaymentDate,
    MAX(PaymentDate) OVER(PARTITION BY YEAR(PaymentDate), MONTH(PaymentDate)) AS MaxPaymentDate,
    ROW_NUMBER() OVER(PARTITION BY PaymentDate ORDER BY ID) AS TieBreaker
  FROM LoanPayments 
  WHERE IsDeleted = 0
  AND ReturnDate is null
) t1
WHERE PaymentDate = MaxPaymentDate AND TieBreaker = 1

这种方法比自连接更有效。

于 2013-07-02T22:44:00.470 回答