There must be a better way to write this, but I’m just not sure what that is. Basically I’m trying to count the distinct values from one column where a condition is met in a separate column. I found this link, but am not sure how to apply it here.
Here is the query, I am using SQL Server 2008R2
SELECT lot,
(SELECT COUNT(DISTINCT d.pid) FROM invdet d WHERE upk = 0 and d.lot = [invdet].lot) as noUpk,
(SELECT COUNT(DISTINCT d.pid) FROM invdet d WHERE upk = 1 and d.lot = [invdet].lot) as isUpk
FROM invdet
WHERE ([status] in ('PQ','P2','FA','F2','BH','RL','SC','LD','PS'))
GROUP BY lot
HAVING COUNT(CASE WHEN invdet.upk = 1 THEN 1 ELSE null END) > 0
You can use the fact that
COUNT DISTINCTdoes not count NULLs to your advantage. In order to examine all the rows, create aWHERE EXISTSclause instead of limiting your result set to those statuses:You can also effectively move the
HAVINGclause into aWHERE EXISTSclause as well, which may be faster, resulting in: