I'm not sure why you need distinct
in (select distinct Workgroup from #grouping)
.
The problem here is that the estimates are off. Without seeing the whole query and the execution plan XML, I'd suggest to try these alternatives:
select
workgroup
andskills
into a #temp table and join to itadd
option(recompile)
to the statement
Each one should be a solution by itself.
It would be benefitial to see the execution plan XML anyway.
EDIT (after reviewing the execution plan, thx for making it available):
This query is over a partitioned view. With check constraints in place, we can see that the partition elimination was done properly, according to runtime value of @startdate and @enddate parameters.
Why optimizer produced different execution plans for the first (one with the subquery) and the second (one with scalar) query?
As far as the optimizer is concerned, it's just a coincidence that the subquery produced only one row. It has to create an execution plan which will be valid for any output from the subquery, be it no rows, one or many.
OTOH, when you specify a scalar value, then optimizer is free to make more straight-forward decisions.
Working with a partitioned view made optimizer's job more difficult, hence my original recommedations showed useless.
Yes, optimizer could probably do a better job here. BTW, are workgroups and skills correlated in any way?