好的,所以我使用此程序的目标是找到与付款承诺的最大日期相匹配的最大付款承诺。我将包括从中提取的过程,因此您将在此处看到 2 个过程。
这第一个过程非常接近我想要它做的事情,但有两个问题。如果 PaymentPromise 表中有 2 个值具有相同的日期,并且该日期是最大值,则将返回两个值。如果 PaymentPromise 中没有值但余额仍然未清,则应在 PaymentPromise 下返回 null 值,但它不会这样做。
SQL Server 2008,如您所知。
ALTER PROCEDURE dbo.GetPaymentsDue
(
@Username varchar(20)
)
AS
DECLARE @BondAmounts TABLE
(
BondID bigint,
BondAmount money,
BondTotal money,
BondBalance money
)
INSERT INTO @BondAmounts EXEC dbo.GetBondAmounts @Username = @Username
SELECT bonds.BondID, Bond.Agency, Bond.Agent, Bond.Defendant, Promise.ExpectedDate,
Promise.ExpectedAmount, bonds.BondTotal, bonds.BondBalance
FROM @BondAmounts bonds
INNER JOIN Bond ON bonds.BondID = Bond.ID
LEFT OUTER JOIN
(
SELECT ID, BondID, ExpectedAmount, ExpectedDate, MAX(ExpectedDate) OVER (PARTITION BY BondID) MaxDate
FROM PaymentPromise
) Promise ON bonds.BondID = Promise.BondID
WHERE bonds.BondBalance > 0
AND (Promise.ExpectedDate = Promise.MaxDate OR Promise.ExpectedDate = NULL)
因此,第一个过程调用第二个过程来获取要使用的初始数据集。
ALTER PROCEDURE dbo.GetBondAmounts
(
@Username varchar(20)
)
AS
SELECT Bond.ID BondID, (ISNULL(Powers.Amount,0) + ISNULL(Charges.Amount,0)) BondAmount,
(ISNULL(BondFee.Amount,0) + ISNULL(Powers.Premium,0) + ISNULL(Charges.Premium,0)
+ ISNULL(Forfeiture.CostOfApprehension,0) + ISNULL(Forfeiture.AmountPaid,0) + Bond.StateTax) BondTotal,
(ISNULL(BondFee.Amount,0) + ISNULL(Powers.Premium,0) + ISNULL(Charges.Premium,0)
+ ISNULL(Forfeiture.CostOfApprehension,0) + ISNULL(Forfeiture.AmountPaid,0) + Bond.StateTax
- ISNULL(BalanceForgiveness.Amount,0) - ISNULL(Payment.Amount,0)) BondBalance
FROM Bond
LEFT OUTER JOIN
(
SELECT Agency, Username FROM UserAgency
WHERE Username = @Username
) AS UserAgency ON Bond.Agency = UserAgency.Agency
LEFT OUTER JOIN
(
SELECT BondID, SUM(AmountForgiven) Amount
FROM BalanceForgiveness
GROUP BY BondID
) AS BalanceForgiveness ON Bond.ID = BalanceForgiveness.BondID
LEFT OUTER JOIN
(
SELECT Bond, SUM(Amount) Amount
FROM BondFee
GROUP BY Bond
) AS BondFee ON Bond.ID = BondFee.Bond
LEFT OUTER JOIN
(
SELECT Powers.Bond, SUM(Charge.BondAmount) Amount,
ISNULL(SUM(Charge.BondPremium), 0) Premium
FROM Powers INNER JOIN Charge ON Powers.Surety = Charge.PowerSurety
AND Powers.PowerPrefix = Charge.PowerPrefix AND Powers.PowerNumber = Charge.PowerNumber
GROUP BY Bond
) AS Powers ON Bond.ID = Powers.Bond
LEFT OUTER JOIN
(
SELECT BondID, SUM(BondAmount) Amount, SUM(BondPremium) Premium
FROM ChargeWithoutPower
GROUP BY BondID
) AS Charges ON Bond.ID = Charges.BondID
LEFT OUTER JOIN
(
SELECT Bond, SUM(CostOfApprehension) CostOfApprehension, SUM(AmountPaid) AmountPaid
FROM Forfeiture
GROUP BY Bond
) AS Forfeiture ON Bond.ID = Forfeiture.Bond
LEFT OUTER JOIN
(
SELECT Bond, SUM(Amount) Amount
FROM Payment
GROUP BY Bond
) AS Payment ON Bond.ID = Payment.Bond
WHERE UserAgency.Username = @Username
OR EXISTS (SELECT * FROM Users WHERE Username = @Username AND Admin = 1)