0

I am formulating a MySQL query that tries to aggregate a COUNT. The data looks like this....table is "workers"

   NAME      DPT
   -----     ----
   CLARK     10
   JAMES     10
   ALLEN     10
   ADAMS     20
   WU        20
   MARTIN    30
   FITZ      30
   SCHMIDT   30
   MILLER    30

I need to list the table like this with a count in the departments

   NAME      DPT   CNT
   -----     ----   ---
   CLARK     10     3
   JAMES     10     3
   ALLEN     10     3
   ADAMS     20     2
   WU        20     2
   MARTIN    30     4
   FITZ      30     4
   SCHMIDT   30     4
   MILLER    30     4

I tried this...

SELECT DISTINCT(NAME), DPT, COUNT(DPT) as CNT FROM workers GROUP BY DPT;

with no success. Pretty sure it's something simple but I'm stumped. Any ideas on where I am going wrong? - JW

0

3 Answers 3

2

Since the count aggregation is on the DPT field only you need to have a subquery for that and then join with the workers table to get the names.

SELECT w.NAME, w.DPT, tot.CNT
FROM workers AS w JOIN (SELECT DPT, COUNT(1) AS CNT FROM workers GROUP BY DPT) AS tot ON w.DPT = tot.DPT 
ORDER BY w.DPT, w.NAME;
Sign up to request clarification or add additional context in comments.

2 Comments

+1, This join would be faster than my subquery, but I'd recommend using an explicit join to make it more readable.
Thanks @Devon, changed it to use an explicit JOIN as you suggested.
0

When you group, you aggregate all the rows under that field. Therefore, you'll only get rows for each distinct value of DPT.

You could use a subquery to get the count for the same DPT value.

SELECT NAME, DPT, (SELECT COUNT(*) FROM workers w2 WHERE w2.DPT = workers.DPT) as CNT
FROM workers;

Comments

0

You could use windowed COUNT(MySQL 8.0 and above):

SELECT *, COUNT(*) OVER(PARTITION BY dpt) AS cnt
FROM workers;

DBFiddle Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.