1

I would like to count rows with the same serv AND spec. The below query counts the rows correctly:

SELECT *, COUNT(*) AS c
FROM table1
GROUP BY serv, spec

But I would like the output displayed as such:

Original:

+-----+------+------+
| id  | serv | spec |
| 500 | 1    | 4    |
| 501 | 5    | 1    |
| 502 | 1    | 4    |
| 503 | 1    | 5    |
| 504 | 5    | 6    |
| 505 | 2    | 4    |
| 506 | 5    | 1    |
| 507 | 2    | 4    |
| 508 | 4    | 3    |
| 509 | 2    | 4    |
+-----+------+------+

Desired output:

+-----+------+------+-------+
| id  | serv | spec | count |
| 500 | 1    | 4    | 2     |
| 502 | 1    | 4    | 2     |
| 503 | 1    | 5    | 1     |
| 505 | 2    | 4    | 3     |
| 507 | 2    | 4    | 3     |
| 509 | 2    | 4    | 3     |
| 508 | 4    | 3    | 1     |
| 501 | 5    | 1    | 2     |
| 506 | 5    | 1    | 2     |
| 504 | 5    | 6    | 1     |
+-----+------+------+-------+
0

1 Answer 1

3

Since MySQL doesn't support window functions, you have do the counts in a subquery, and then join this subquery to the table:

SELECT t.id, t.serv, t.spec, c.cnt
FROM
  table1 t INNER JOIN (
    SELECT serv, spec, COUNT(*) as cnt
    FROM table1
    GROUP BY serv, spec
  ) c ON t.serv = c.serv AND t.spec=c.spec
Sign up to request clarification or add additional context in comments.

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.