2

我有一个包含以下内容的佣金表:

Lower    Upper     Percentage
0        300       45
300.01   800       50
800.01   1500      55

上下金额是货币价值,我需要使用与总销售额相关的百分比金额,根据总销售额计算累计支付金额。

如果我的总销售额为 350,我的佣金应计算如下:

总数中的前 300 个将使用 45%,其余 50 个将使用 50%,所以我的总数将是
300*45% = 135
50*50% = 25
Total = 160

我正在通过 sproc 更新带有金额的表格,因此需要在其中容纳此内容。

最好的方法是什么?

注意:下面的 sproc 具有正确的列名,如上面的示例,为简单起见,我更改了列名。SPROC还加入了存储bands的表,更新表是一种工作/报告表


编辑:存储过程更新部分:

UPDATE CommissionCalculationDetails
SET TotalCommissionAmount = 
case
  when TotalSales > Upper then Upper
  when TotalSale > Lower then @sales - Lower
  else 0
end 
* Percentage / 100
FROM CommissionCalculationDetails
LEFT JOIN CommissionBand 
ON TotalSales > CommissionBand.Lower
AND TotalSales < CommisionBand.Upper
4

1 回答 1

5

我建议您改为存储非包容性下限(例如:300而不是300.01),并在与它进行比较时严格使用大于。就目前而言,该值300.005不会被正确分类。

如果是这种情况,您可以使用以下查询计算总佣金:

select
  sum (
    case
      when @sales > Upper then Upper
      when @sales > Lower then @sales - Lower
      else 0
    end 
    * Percentage / 100
  ) as TotalCommission
from CommissionTable

这是一个在线测试版本:http ://www.sqlfiddle.com/#!3/87f12/8


Slightly offtopic: Your table currently contains redundant information; each lower bound is (more or less) equal to the previous upper bound. Although this is not essential, you could think of a way to store, for example, upper bounds only (and have a null signifying unbounded).


For the update, one possible solution is to extract the commission calculation in a function, like so:

create function ufn_CalculateCommission(@Sales money) 
  returns money 
as
begin

  declare @result money

  select 
    @result = 
      sum (
        case
          when @sales > Upper then Upper
          when @sales > Lower then @sales - Lower
          else 0
        end 
        * Percentage / 100
      )
  from CommissionBand

  return @result
end

After declaring the function, the update can be simplified to:

update CommissionCalculationDetails
set TotalCommissionAmount = dbo.ufn_CalculateCommission(TotalSales);

Here's how it works: http://www.sqlfiddle.com/#!3/f4405/4

于 2013-08-02T09:36:07.587 回答