Hello Friends,
I 'm in need of some SQL help please, I have an SQL example below with the following conditions:
All REG plus SICK hours cannot exceed 40 hours in that week.
The calculation for REG hours is: total no. of REG hours in a Cost Center Divided By total no of all REG Hours regardless of Cost Center times (40 minus SICK hours)
In the example below:
For WEEK 1 - Total number of REG hours regardless of Cost Centers are 55 hours with 8 SICK hours.
REG hours in Cost Center 123 = 55 hours
SICK hours regardless of Cost Center = 8 hours
So it would be REG hours = 55/55 x (40 -8) = 32 Hours
Then SICK hours = 8, so the total hours sent that week = 40
For WEEK 2 - Total number of REG hours regardless of Cost Centers are 50 hours with 4 SICK hours.
REG hours in Cost Center 123 = 25 hours
So it would be REG hours = 25/50 x (40 -4) = 18 Hours
REG hours in Cost Center 456 = 25 hours
So it would be REG hours = 25/50 x (40 -4) = 18 Hours
Then SICK hours = 4, so the total hours sent that week = 40
What I have tried:
This is what I have tried so far. I can get data right for week1, I just don't know how to add week2 in there to get desired results.
;WITH SampleData (PERSON, [COSTCENTER],[AMOUNT], [PAYCODE],[DATE],WEEKINDICATOR) AS
(
SELECT 101,'123',CAST('13.00' AS decimal(5, 2)),'REG','04/26/2021','1'
UNION ALL SELECT 101,'123','08.00','SICK','04/30/2021','1'
UNION ALL SELECT 101,'123','58.00','ALL','04/30/2021','1'
UNION ALL SELECT 101,'123','25.00','REG','04/26/2021','2'
UNION ALL SELECT 101,'456','25.00','REG','04/29/2021','2'
UNION ALL SELECT 101,'123','04.00','SICK','04/30/2021','2'
UNION ALL SELECT 101,'123','54.00','ALL','04/30/2021','2'
),
cc_totals(person, costcenter, paycode, sum_amount) as (
select person, costcenter, paycode, sum(amount)
from SampleData where paycode <> 'ALL' and WEEKINDICATOR = 1
group by person, costcenter, paycode),
totals(person, reg_amount, sck_amount) as (
select person,
sum(case when paycode='reg' then sum_amount else 0 end),
sum(case when paycode='sick' then sum_amount else 0 end)
from cc_totals
group by person)
select t1.person, t1.paycode, t1.costcenter,
case when t1.paycode='reg'
then (t1.sum_amount/t2.reg_amount)*(40-t2.sck_amount)
else t2.sck_amount end amount
from cc_totals t1
join totals t2 on t1.person = t2.person
union all
select person, costcenter, paycode, amount
from SampleData where paycode = 'ALL' and WEEKINDICATOR = 1