0

Is there any way to use COUNT and return with a COUNT column for each row. If i were to use GROUP BY it would only return 1 row for each value. I want it to show duplicates.

Example Data:

City
Seattle
Dallas
Seattle
New York
Boston
Boston
Portland

I would like to return:
Seattle 2
Dallas 1
Seattle 2
New York 1
Boston 2
Boston 2
Portland 1

0

2 Answers 2

3

you can use correlated subquery.

SELECT  a.City,
        (SELECT COUNT(*) FROM tableName b WHERE a.City = b.City) totalCount
FROM    tableName a
Sign up to request clarification or add additional context in comments.

Comments

2

You can join the original table with a subquery that uses GROUP BY:

SELECT t1.city, citycount
FROM myTable t1
JOIN (SELECT city, COUNT(city) citycount
      FROM myTable
      GROUP BY city) t2
USING (city)

SQLFIDDLE

2 Comments

@fthiella Thanks. Maybe because I didn't add a sqlfiddle like 491243 did. Fixed that.
@491243 Maybe because we forgot to tell the OP not to use the mysql_ extensions, even though there's no PHP in the question? :)

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.