[英]sql variable on select statement
嘗試創建一個具有應付余額,利息費用,應付總額和付款計划的結果集。 他們以我的方式編碼它似乎可以工作,但是看起來很不雅致。 有沒有一種方法可以利用變量使代碼更清晰?
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
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
使用虛擬表。 除此之外,做得很好。 :-)
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.