1

我有一个像这样的客户折扣表: 在此处输入图像描述

我有一个名为 @Total 的 deeared varialbe 来存储总金额

declare @Total numeric (12,2)

set @Total = (select Sum(LaborAmt) from #Data
              group by Co) 

我需要编写一个查询来根据@Total 获得更正的 discountRate。这意味着如果我的总金额为 3500000,它应该返回 2

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) .........

对不起,我只是不知道必须写它

4

2 回答 2

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 
于 2013-02-26T19:19:15.520 回答
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

希望这有助于为您澄清事情。

于 2013-02-26T19:19:17.097 回答