好吧,所以我知道这是一个很大的程序,但我的问题很简单。我试图从中获取一个Bond的单个实例,但是由于我是管理员,它给了我每个实例的系统中与该代理相关的用户数。这发生在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)
答案 0 :(得分:1)
好的,所以我找到了自己的答案。我只需要使UserAgency与其他连接相同。以下是它的外观:
LEFT OUTER JOIN
(
SELECT Agency, Username FROM UserAgency
WHERE Username = @Username
) AS UserAgency ON Bond.Agency = UserAgency.Agency