さて、これが大規模な手順であることはわかっていますが、私の質問は非常に簡単です。これからボンドの単一のインスタンスを取得しようとしていますが、私は管理者であるため、各インスタンスにエージェンシーに関連するシステム内のユーザー数を掛けています。これは、OR EXISTS ステートメントがある下部で発生します。必要な金額に対して正しい結果を取得しながら、結果を各結合の 1 つに制限する方法を理解する助けが必要です。そのため、個々の結合ステートメントが必要です。
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 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)