Query to get sum of an employees commission

孤者浪人 提交于 2019-12-12 04:34:11

问题


Query to get total commissions for an employee, and update their totalCommission column in the employee table.

This query is run every few days (batch).

The rules: 1. an employee can only get a maximum of $100/day of commision, if they get more than $100 it just gets set to $100.

Tables:

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

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

Using SQL Server 2005.

So this query will have to group by day I presume, and use a case statement to set the daily commision to $100 if the sum is > 100 for that day, and then set the total SUM for all days to the Employee.TotalCommission column.


回答1:


assuming you are limiting the dates somewhere using value of "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


来源:https://stackoverflow.com/questions/1658421/query-to-get-sum-of-an-employees-commission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!