I think this is what you want:
with d as (
select RR.REPID, RR.ReportDate, RR.Score, RR.CategoryID,
row_number() over(partition by RR.REPID, RR.ReportDate order by RR.Score) rn
from REPREPORTING RR
JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID -- right here
Where RR.RepID <> 0
)
select
d.REPID, d.ReportDate,
max(case when d.CategoryID = 5001 then d.Score end) InPercent,
max(case when d.CategoryID = 5002 then d.Score end) OutPercent
from
d
group by
d.REPID, d.ReportDate
I moved your subquery d
into a CTE for readability, so don't read too much into that.
You could move the join to the outer query (d), but it's more efficient to eliminate rows before invoking grouping function -- the fewer rows you need to group, the better your query will run.
That said, once I did this I couldn't help but notice that your rn
field, which invokes a windowing function, doesn't appear to have any impact. Did you mean to use this, perhaps to take only the first row:
with d as (
select RR.REPID, RR.ReportDate, RR.Score, RR.CategoryID,
row_number() over(partition by RR.REPID, RR.ReportDate order by RR.Score) rn
from REPREPORTING RR
JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID
Where RR.RepID <> 0
)
select
d.REPID, d.ReportDate,
max(case when d.CategoryID = 5001 then d.Score end) InPercent,
max(case when d.CategoryID = 5002 then d.Score end) OutPercent
from
d
where
d.rn = 1 -- Did you mean to add this?
group by
d.REPID, d.ReportDate
If not, I think you can completely avoid the CTE/subquery altogether and eliminate the windowing function (row_number
), which while one of my favorite functions, does have some cost associated with it:
select
RR.REPID, RR.ReportDate,
max(case when RR.CategoryID = 5001 then RR.Score end) InPercent,
max(case when RR.CategoryID = 5002 then RR.Score end) OutPercent
from
from REPREPORTING RR
JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID
group by
RR.REPID, RR.ReportDate
And, of course, the VBA version:
sql = _
"select " & _
" RR.REPID, RR.ReportDate, " & _
" max(case when RR.CategoryID = 5001 then RR.Score end) InPercent, " & _
" max(case when RR.CategoryID = 5002 then RR.Score end) OutPercent " & _
"from " & _
" from REPREPORTING RR " & _
" JOIN EMPCUR_EmployeeCurr P ON P.employee_token_nr = RR.REPID " & _
"group by " & _
" RR.REPID, RR.ReportDate"