Question : Tiered commission calculation in SQL - How to calculate?

In a company there are 2 groups of people. One group gets paid on commission 50% for all gross revenue they bring in. Another group gets paid on commission, but on a tiered basis. That is, someone can make:

            50% on 0 to 100,000
            55% on 100,001 to 250,000
            60% on 250,001 and above

Someone in the tiered group has been working since Jan 1 and has passed the 150,000 mark on March 15th. The current date is April 30 and his total gross revenues year to date are 300,500. This is just one person in the group. Others have different total gross revenues year to date.

How would you structure the DB and calculate their total commissions year to date?

 

Answer : Tiered commission calculation in SQL - How to calculate?

Whew, this is trickier than it sounds!
I think the code below works.  I tried to avoid a function just because of the overhead.

--create sample/test data
DROP TABLE commissions
CREATE TABLE commissions (
    tier TINYINT,
      flag TINYINT,
      lowValue DECIMAL(12, 2),
      highValue DECIMAL(12, 2),
      pct DECIMAL(3, 2)
      )
INSERT INTO commissions VALUES(0, 0,      0,     2147483647,  0.50) --default commission
INSERT INTO commissions VALUES(1, 1,      0,         100000,  0.50)
INSERT INTO commissions VALUES(2, 1, 100000.01,      250000,  0.55)
INSERT INTO commissions VALUES(3, 1, 250000.01,  2147483647,  0.60)

DROP TABLE revenues
CREATE TABLE revenues (
      empNum INT,
      gross DECIMAL(12, 2),      
      commissionFlag TINYINT
      )
INSERT INTO revenues VALUES(1111111, 300500, 1)
INSERT INTO revenues VALUES(2222222, 300500, 0)


SELECT rev.empNum, rev.gross,
      SUM(CASE WHEN rev.gross > com.highValue
               THEN com.highValue - com.lowValue + CASE WHEN com.lowValue <> 0 THEN .01 ELSE 0 END
               ELSE rev.gross - com.lowValue + CASE WHEN com.lowValue <> 0 THEN .01 ELSE 0 END END * com.pct)
      AS [commission]
FROM revenues rev
INNER JOIN commissions com ON rev.commissionFlag = com.flag AND
      rev.gross >= com.lowValue
GROUP BY rev.empNum, rev.gross
Random Solutions  
 
programming4us programming4us