I am having some trouble with a query and was hoping someone could help. I have tried searching for a solution, but can’t seem to find a similar scenario with my search terms.
Here is what I am looking for:
I have a table with three columns and need to return the values in the first column, and two counts of the values in the second column. One count is based on a parameter and the other is the total count. Ideally, I would only like to return the values in column one that have equal counts.
For example:
Part Number | Make ID
ABC123 | 1<br>
ABC123 | 1<br>
ABC123 | 3<br>
DEF456 | 1<br>
DEF456 | 1
Part Number | Count of Apps Where Make ID = 1| Count of Total Apps
ABC123 | 2 | 3
DEF456 | 2 | 2
The query I have so far will return the total count of apps for part numbers that have the parameter value, but I need it to return both counts:
SELECT apps.part#,
COUNT(DISTINCT application#)apps
FROM [mytable] AS apps
INNER JOIN (SELECT part#
FROM [mytable]
WHERE make = '1') AS sz
ON sz.part# = apps.part#
GROUP BY apps.part#
ORDER BY 1
Any help is greatly appreciated!
Thanks, everyone! I received several correct answers, and selected the one that was give first:
SELECT part#,
COUNT(DISTINCT CASE WHEN make = '1' THEN application# END) make1_apps,
COUNT(DISTINCT application#) total_apps
FROM [mytable]
GROUP BY part#
HAVING COUNT(DISTINCT CASE WHEN make = '1' THEN application# END)
= COUNT(DISTINCT application#)
ORDER BY part#
Thanks again!
The HAVING clause ensures the two counts match.