0

I can get a count of the number of times each element occurs using the following MySQL

SELECT COUNT(*) AS count
FROM example
GROUP BY example.value

The problem is, because of the GROUP BY statement, duplicate records will not be returned with their COUNT value.

IE I need this:

  1. apples - 2
  2. apples - 2
  3. oranges - 1
  4. bananas - 3
  5. bananas - 3
  6. bananas - 3

But I get this:

  1. apples - 2
  2. oranges - 1
  3. bananas - 3

Any ideas how this could be done? I am thinking some kind of a join, but I can't figure out the proper way to compare the table to itself

2 Answers 2

2

You can use JOIN:

select a.*, b.cnt
from example a
join (
    select value, count(*) cnt
    from example
    group by value
    ) b on a.value = b.value;
Sign up to request clarification or add additional context in comments.

Comments

2
SELECT e.value, t.count 
FROM example e
LEFT JOIN (SELECT value, COUNT(*) AS count
  FROM example
  GROUP BY example.value) t
ON e.value = t.value;

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.