Error: Invalid object name. I want to input some sample data.
here is the code:
DECLARE
@tbl_paycode TABLE
(
personnum VARCHAR(32),
paycode VARCHAR(32),
hours INT
);
INSERT @tbl_paycode VALUES
('100444', 'REG', 8),
('100444', 'OTC', 2),
('700000', 'REG', 38),
('800000', 'VAC', 12),
('900000', 'REG', 35);
DECLARE
@tbl_transfercode TABLE
(
personnum VARCHAR(32),
transfercode VARCHAR(32),
hours INT
);
INSERT @tbl_transfercode VALUES
('100444', 'Outside', 4),
('100444', 'Inside', 6),
('700000', 'Outside', 20),
('700000', 'Inside', 18),
('800000', 'Inside', 12),
('900000', 'Inside', 35);
;
with cte_paycode1
as (select personnum
,paycode
,[hours]-1 as rest
from tbl_paycode
union all
select personnum
,paycode
,rest-1 as rest
from cte_paycode1 as a
where rest>0
)
/* Make ready to join in right order /
,cte_paycode2
as (select personnum
,paycode
,row_number() over(partition by personnum
order by case
when paycode='REG' then 0
else 1
end
,paycode
)
as rn
from cte_paycode1
)
/ Break into single hour /
,cte_transfercode1
as (select personnum
,transfercode
,[hours]-1 as rest
from tbl_transfercode
union all
select personnum
,transfercode
,rest-1 as rest
from cte_transfercode1 as a
where rest>0
)
/ Make ready to join in right order /
,cte_transfercode2
as (select a.personnum
,a.transfercode
,row_number() over(partition by a.personnum
order by b.[hours] desc
)
as rn
from cte_transfercode1 as a
inner join tbl_transfercode as b
on b.personnum=a.personnum
and b.transfercode=a.transfercode
)
/ Now join and sum it all up /
select a.personnum
,a.paycode
,count() as [hours]
,b.transfercode
from cte_paycode2 as a
left outer join cte_transfercode2 as b
on b.personnum=a.personnum
and b.rn=a.rn
group by a.personnum
,a.paycode
,b.transfercode
order by a.personnum
,case
when a.paycode='REG' then 0
else 1
end
,a.paycode
,count(*) desc
,b.transfercode desc
;