select语句中的sql变量

时间:2013-04-16 04:28:49

标签: sql variables

尝试创建具有到期余额,利息费用,到期总额和付款计划的结果集。他们编码的方式似乎有效,但看起来非常不优雅。有没有办法利用变量来使代码更清晰?

SELECT 
    CustFName, CustLName, CustPhone, 
    SUM(InvoiceAmount - PaymentAmount) AS BalanceDue,
    SUM(InvoiceAmount - PaymentAmount)*.195 AS InterestCharge,
    SUM(InvoiceAmount - PaymentAmount) + SUM(InvoiceAmount - PaymentAmount) *.195 AS TotalDue,
    (SUM(InvoiceAmount - PaymentAmount) + SUM(InvoiceAmount - PaymentAmount) *.195)/4 AS PaymentPlan
FROM 
    Customer 
JOIN 
    Vehicle ON Customer.CustomerID = Vehicle.CustomerID
JOIN 
    Invoice ON Vehicle.VehicleID = Invoice.VehicleID
WHERE 
    InvoiceAmount - PaymentAmount > 400
GROUP BY 
    CustFName, CustLName, CustPhone

2 个答案:

答案 0 :(得分:0)

DECLARE @p FLOAT
SET @p = 0.195
SELECT CustFName, CustLName, CustPhone, SUM(InvoiceAmount - PaymentAmount) AS BalanceDue,
    SUM(InvoiceAmount - PaymentAmount)*@p AS InterestCharge,
    SUM(InvoiceAmount - PaymentAmount) + SUM(InvoiceAmount - PaymentAmount) *@p AS TotalDue,
    (SUM(InvoiceAmount - PaymentAmount) + SUM(InvoiceAmount - PaymentAmount) *@p)/4 AS PaymentPlan

FROM Customer JOIN Vehicle
    ON Customer.CustomerID = Vehicle.CustomerID
    JOIN Invoice
    ON Vehicle.VehicleID = Invoice.VehicleID

WHERE InvoiceAmount - PaymentAmount > 400

GROUP BY CustFName, CustLName, CustPhone

答案 1 :(得分:0)

使用虚拟表。除此之外,做得很好。 : - )

SELECT 
    CustFName, CustLName, CustPhone, 
    BalanceDue,
    BalanceDue * Factor AS InterestCharge,
    BalanceDue + BalanceDue * Factor AS TotalDue,
    (BalanceDue + BalanceDue * Factor)/4 AS PaymentPlan
from (
        SELECT 
            CustFName, CustLName, CustPhone, 0.195 as Factor
            SUM(InvoiceAmount - PaymentAmount) AS BalanceDue
        FROM 
            Customer 
        JOIN 
            Vehicle ON Customer.CustomerID = Vehicle.CustomerID
        JOIN 
            Invoice ON Vehicle.VehicleID = Invoice.VehicleID
        WHERE 
            InvoiceAmount - PaymentAmount > 400
        GROUP BY 
            CustFName, CustLName, CustPhone
) as A;