0

I have a MySQL view with the fields id and set. Because it's a view, most ids are repeated and have duplicate entries. For example, and id = 120158 may have 5 rows, 3 where set = A and 2 where set = B. I want to run a query off of the view to display the number of rows each id has associated with its corresponding sets. I tried:

SELECT `id`, 
    `set`,
    (SELECT COUNT(set)) AS `CountOfSet`
FROM `view1`

However, this simply returns the same view (duplicate rows still exist) with CountOfSet equal to 1 for every row. Any ideas?

2 Answers 2

1

You should be grouping your results by id and set to get the desired result:

SELECT `id`, `set`, COUNT(*) AS `CountOfSet` FROM `view1`
GROUP BY `id`, `set`

This would return the results as

120158 A 3
120158 B 2
Sign up to request clarification or add additional context in comments.

Comments

0

You need to group your data using GROUP BY clause:

GROUP BY `id`, `set`

Composing all together:

SELECT `id`, 
`set`,
COUNT(*) AS `CountOfSet`
FROM `view1`
GROUP BY `id`, `set`

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.