views:

60

answers:

1

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.

+2  A: 

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
davek
Is DAY(created) safe? will it confuse jan.21 and feb.21 , etc. as all being the same day? (since it is ignoring the month/year?)
mrblah
DAY(date) gives you the day portion of your date - for both Jan.21 and Feb.21, you'll get "21" as the value
marc_s
marc_s so then the query won't work, since jan.21 and feb.21 are different days, I guess you have to break down the date forther to include month/year also.
mrblah