What this query does:
Gets multiple users with the first
select
in theunion
; those are the active users.But when a user is not in that list, but there is a
@userid
, it should get that user as well and set active to 0 there; that is what the secondselect
does.If a user is in the first
select
, and in the secondselect
, the second one should not be in theresultset
; that is what thegroup by
with themax
is for.
Is there a more efficient way to write this query?
SELECT pk_userid,
username,
CAST(MAX(active) AS BIT) AS active
FROM (SELECT pk_userid,
username,
1 AS active
FROM dbo.tbluser u
INNER JOIN tblCustomer c ON u.pk_userid = c.fk_userid
WHERE ( c.fk_projectid = @projectid
AND c.fk_orderid = @orderid )
UNION
SELECT pk_userid,
username AS username,
0 AS active
FROM dbo.tbluser u
WHERE pk_userid = @userid) a
GROUP BY pk_userid,
username
ORDER BY username