Use results from one SQL statement to do a count in another statement

Viewed 43

Excel has reached its limits with my data so I'm trying SQL. I am using SQL Server 2019 Express.

I am trying to count the number of unique employee names per GM in the table. Each row of employee is a different project that employee has worked on. For the example below the count for gm1 would be three unique employees and not four as that is the number of records.

Employee  GM
--------------
ee1       gm1
ee1       gm1
ee2       gm1
ee3       gm1
ee4       gm2
ee5       gm2
ee6       gm2
...

I have these two SELECT statements that I'm trying to merge.

SELECT COUNT(DISTINCT EeNumber) AS GMCOUNT
FROM WOWEEs
WHERE GM = '#N/A';

SELECT DISTINCT GM 
FROM WOWEEs;

The result should look like

GM    Count
------------
gm1   3
gm2   3
1 Answers

You need to use a group by clause:

SELECT   gm, COUNT(DISTINCT eenumber)
FROM     wowees
GROUP BY gm
Related