我有这样的客户折扣表:
我有一个名为@Total的deceared varialbe来存储总金额
declare @Total numeric (12,2)
set @Total = (select Sum(LaborAmt) from #Data
group by Co)
我需要编写一个查询来根据@Total获取更正后的discountRate。这意味着如果我的总金额是3500000
,它应该返回2SELECT dbo.budCustomerDisc.Customer, dbo.budCustDiscRate.DiscountRate
FROM dbo.budCustDiscRate INNER JOIN
dbo.budCustomerDisc ON dbo.budCustDiscRate.DiscountID = dbo.budCustomerDisc.DiscountId AND dbo.budCustDiscRate.JBCo = dbo.budCustomerDisc.JBCo
WHERE (dbo.budCustomerDisc.Customer = 165) .........
抱歉,我只是不知道要写它
答案 0 :(得分:2)
SELECT budCustomerDisc.Customer, budCustDiscRate.DiscountRate
FROM budCustDiscRate
INNER JOIN dbo.budCustomerDisc ON dbo.budCustDiscRate.DiscountID = dbo.budCustomerDisc.DiscountId AND dbo.budCustDiscRate.JBCo = dbo.budCustomerDisc.JBCo
WHERE budCustomerDisc.Customer = 165
And BegBillAmt <= @Total
And EndBillAmt >= @Total
答案 1 :(得分:1)
这里的关键是,当@Total介于BegBillAmt和EndBillAmt之间时,您正在寻找它返回值。您希望它返回正确的DiscountRate。为此,我们需要BETWEEN语句或两个语句,一个检查BegBillAmt,一个检查EndBill Amt。我将说明两者:
首先使用BETWEEN:
SELECT dbo.budCustomerDisc.Customer, dbo.budCustDiscRate.DiscountRate
FROM dbo.budCustDiscRate INNER JOIN
dbo.budCustomerDisc ON dbo.budCustDiscRate.DiscountID = dbo.budCustomerDisc.DiscountId AND dbo.budCustDiscRate.JBCo = dbo.budCustomerDisc.JBCo
WHERE (dbo.budCustomerDisc.Customer = 165) AND @TOTAL BETWEEN BegBillAmt AND EndBillAmt
有时BETWEEN不清楚(哎呀我不确定它是在SQL Server之外支持的,或者在那种情况下它们是数据库字段而不是静态变量)。所以这里有两个检查:
SELECT dbo.budCustomerDisc.Customer, dbo.budCustDiscRate.DiscountRate
FROM dbo.budCustDiscRate INNER JOIN
dbo.budCustomerDisc ON dbo.budCustDiscRate.DiscountID = dbo.budCustomerDisc.DiscountId AND dbo.budCustDiscRate.JBCo = dbo.budCustomerDisc.JBCo
WHERE (dbo.budCustomerDisc.Customer = 165) AND BegBillAmt >= @Total AND EndBillAmt <= @Total
希望这有助于为您澄清事情。