Avatar of fadiel ras
fadiel ras
 asked on

Tiered commission calculation in SQL - How to calculate?

I'm having the exact same problem as poster: tmyint had a few years back (a good few years)
View the original post and solution of poster: tmyint.

I trying to understand what the .01 in Scotts solution refers to, does any one know why in the CASE statement, inside the accepted solution he uses this "THEN .01"

I'll paste the exact code, in for quicker reference than the link

--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

Open in new window

Microsoft SQL ServerMySQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
fadiel ras

8/22/2022 - Mon
PortletPaul

I believe Scott is adding up percentages.
I.e.
Sum (.01)
Results in the total percentage to apply


Quite crafty actually.
fadiel ras

ASKER
Thanks Paul. I'm not exactly following, but let me check in more detail and revert asap
ASKER CERTIFIED SOLUTION
PortletPaul

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
fadiel ras

ASKER
Thanks Paul, I get it now, appreciate the fast response.
PS - I'm posting a related, but different question in a few minutes, hopefully you'll again be able to help, thank you
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes