2

我有这个 SQL 查询,

SELECT PaymentID, CustomerID, PaymentDate, Amount, Balance, Credit 
FROM Payment 
WHERE (PaymentDate = '2012-11-03')

我还喜欢打印客户上次交易的余额和信用表格。
这是我的尝试。

SELECT DISTINCT TOP 1 Balance, Credit, PaymentID 
FROM Payment 
WHERE CustomerID = '??' AND PaymentID < '??'
ORDER BY PaymentID DESC

如您所见,这没有任何作用,因为不喜欢查询。我想我必须使用 T-SQL 或 UNION 但不知道如何实现它。

我试图实现的这种输出。

在此处输入图像描述

付款表

PaymentID   int 
CustomerID  varchar(50)
PaymentDate date
Amount  decimal(18, 2)
Balance     decimal(18, 2)
Credit  decimal(18, 2)

笔记:

这不仅适用于单个客户,还适用于所有客户,就像销售报告一样。每位客户一天内可以进行多次付款。

4

1 回答 1

0

这可能会让你开始

SELECT P1.paymentID, P1.CustomerID, P1.PaymentDate, max(PP.paymentID)
FROM Payment P1 
Join Payment PP 
  on PP.paymentID < P1.paymentID 
 and PP.CustomerID = P1.CustomerID
 and P1.PaymentDate = '2012-11-03'
GroupBy P1.paymentID, P1.CustomerID, P1.PaymentDate


not test but I think this will pull in the other data

select PC.*, PL.PaymentDate,  PL.Amount,  PL.Balance,  PL.Credit 
from 
(SELECT P1.paymentID, P1.CustomerID, P1.PaymentDate, max(PP.paymentID) as PriorPID
FROM Payment P1 
Join Payment PP 
  on PP.paymentID < P1.paymentID 
 and PP.CustomerID = P1.CustomerID
 and P1.PaymentDate = '2012-11-03'
GroupBy P1.paymentID, P1.CustomerID, P1.PaymentDate) as PC 
join Payment PL 
  on PL.paymentID = PC.PriorPID 
 and PL.CustomerID = PC.CustomerID 
于 2012-12-04T23:17:15.527 回答