with
-- Generate the Pay Code Table using VP_TOTALS
Tbl_PCode as (
SELECT ROW_NUMBER() OVER(ORDER BY a.PERSONNUM DESC) AS pos,
a.PERSONNUM as ID,
a.APPLYDATE as Date,
a.PAYCODENAME as PCode,
(sum(a.TIMEINSECONDS * 1.0)/3600) as Hours,
b.PAYRULENAME
FROM
VP_TOTALS a
LEFT OUTER JOIN VP_ALLPERSONV42 b
ON a.PERSONNUM = b.PERSONNUM
where
(a.LABORLEVELNAME1 = '87') and (a.paycodetype = 'P') and (b.HOMELABORLEVELNM1 = '87') and (b.payrulename LIKE 'Hour%')
and (a.applydate between '8-22-2016' and '9-4-2016')
group by
a.[PERSONNUM],[applydate],[PAYCODENAME], [PAYRULENAME]
),
-- Generate the Transfer Code Table using VP_TIMESHEETITMV42
Tbl_TCode as (
SELECT ROW_NUMBER() OVER(ORDER BY a.PERSONNUM DESC) AS pos,
a.PERSONNUM as ID,
a.EVENTDATE as Date,
a.WORKRULENAME as TCode,
(sum(DATEDIFF (second,a.STARTDTM,a.ENDDTM)) * 1.0/3600 ) as Hours,
b.PAYRULENAME
FROM
VP_TIMESHEETITMV42 a
LEFT OUTER JOIN VP_ALLPERSONV42 b
ON a.PERSONNUM = b.PERSONNUM
where (a.LABORLEVELNAME1 = '87') and (b.payrulename LIKE 'Hour%') and (a.eventdate between '8-22-2016' and '9-4-2016')
group by a.[PERSONNUM],[EVENTDATE],[WORKRULENAME],[payrulename]
),
tally as (
select top(500000) rn= row_number() over(order by (select null))
from sys.all_objects
),
-- Layout the SQL Query
t_P as (
select *, rn=row_number() over(partition by ID,Date order by pos)
from Tbl_PCode
cross apply (select top(Hours) 1 n
from tally
) x
),
t_T as (
select *, rn=row_number() over(partition by ID,Date order by pos)
from Tbl_TCode
cross apply (select top(Hours) 1 n
from tally
) x
)
select t_P.ID as PersonNum, t_P.PCode as [Pay Code],
count(*) as Hours,
t_T.TCode as [Transfer Code]
from t_P
join t_T on t_P.ID=t_T.ID and t_P.Date=t_T.Date and t_P.rn=t_T.rn
group by t_P.ID, t_P.PCode, t_T.TCode