2013-02-26 178 views
1

我有這樣的一個客戶折扣表: enter image description here計算折扣

我有一個名爲@Total一個deceared varialbe存儲總量

declare @Total numeric (12,2) 

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

我需要編寫一個查詢,得到正確的根據@Total的折扣率。這就是意味着它應該返回2,如果我的總量是350萬

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

對不起,我只是不知道有寫它

+0

發佈您的表格結構和期望的結果,我們可能會使這更容易。 – sgeddes 2013-02-26 19:20:29

回答

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 

有時之間還不清楚(赫克我不知道它是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 

希望這有助於澄清事情給你。

+0

我有四種不同的discountRate,使用不同的begbillAmt和EndBillAmt無法綁定多部分標識符「budCustomerDisc.Customer」。 – 2013-02-26 19:23:58

+0

@ user1723572你的內部連接不正確或缺失。我已經用完整的查詢更新了我的答案。這兩個都應該做你需要的。 – 2013-02-26 19:33:53

+0

非常感謝你。它確實有效。今天我的思想就停止工作。 :) – 2013-02-26 19:47:09

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 
+0

無法綁定多部分標識符「budCustomerDisc.Customer」。 – 2013-02-26 19:26:29

+0

@ user1723572注意不同的表名稱。此查詢缺少內部聯接。 – 2013-02-26 19:36:04