Please look at the below query
select
DATEADD(wk, DATEDIFF(wk, 6, creation_ts), 6) creation_ts
,sum(case when (priority = 'P1') then 1 else 0 end) as P1
,sum(case when (priority = 'P2') then 1 else 0 end) as P2
,sum(case when (priority = 'P3') then 1 else 0 end) as P3
,sum(case when (priority = 'P4') then 1 else 0 end) as P4
,sum(case when (priority = 'P5') then 1 else 0 end) as P5
,count(*) Total
from dbo.BugzillaTrans
where
(cf_projectnumber = @Project_Number or @Project_Number is null)
and (product_id = @product_id or @product_id is null)
and (component_id = @component_id or @component_id is null)
and (creation_ts >= @Start_Dt or @Start_Dt is null)
and (creation_ts <= @End_Dt or @End_Dt is null)
and priority in ('P1','P2','P3','P4','P5')
and assigned_to in (select EmailAddress from dbo.users where role_id = @role_id or @role_id is null)
and assigned_to in (select EmailAddress from dbo.users where team_id = @team_id or @team_id is null)
and assigned_to in (select EmailAddress from dbo.users where location_id = @location_id or @location_id is null)
group by DATEADD(wk, DATEDIFF(wk, 6, creation_ts), 6)
As can be figure out that inside the where clause I am using a SELECT clause to fetch record from users table.
and assigned_to in (select EmailAddress from dbo.users where role_id = @role_id or @role_id is null)
and assigned_to in (select EmailAddress from dbo.users where team_id = @team_id or @team_id is null)
and assigned_to in (select EmailAddress from dbo.users where location_id = @location_id or @location_id is null)
How can this be avoided and write in a different fashion?
OR can there be any better way(obviously I am sure, there will be) of writing this entire program?
Thanks
There are (as you point out) probably a million ways to rewrite this query as a whole, but the specific question you ask about avoiding the sub-selects can be answered with an
inner join.