查询获得员工佣金的总和

时间:2009-11-01 21:37:06

标签: sql-server sql-server-2005

查询获取员工的总佣金,并更新员工表中的totalCommission列。

此查询每隔几天运行一次(批处理)。

规则: 1. 一名员工最多可以获得每天100美元的佣金,如果他们的收入超过100美元,则只需设置为100美元。

表:

Employee 
  (employeeID INT PK, totalCommissions INT, username, ...)

Sale 
  (saleID INT PK, employeeID INT FK, saleTotal, commission, created DATETIME)

使用SQL Server 2005。

因此,这个查询必须按照我假设的日期进行分组,并使用case语句将每日佣金设置为$ 100(如果总和为>当天为100,然后将所有日期的总SUM设置为Employee.TotalCommission列。

1 个答案:

答案 0 :(得分:2)

假设您使用“somedate-goes-here”的值限制日期:

update employee set totalcommissions = totalc
from
(
-------------------------------------
-- sum capped commissions by employee
-------------------------------------
select employeeID, sum(sum_commissions) as totalc from
      (
      ---------------------------------------
      -- make sure sum is capped if necessary
      ---------------------------------------
              select employeeID
              , case when sum_of_c > 100 then 100 else sum_of_c as sum_commisions
              from 
              (
              -----------------------------------------------
              -- get sum of  commissions per day per employee
              -----------------------------------------------
              select employeeID, sum(commission) as sum_of_c from sale
              where created > "somedate-goes-here"
              group by employeeID, day(created)
              ) as x
      ) as c
  group by employeeID
) y 
inner join employee on employee.employeeID = y.employeeID