Reputation: 17
I have a MySQL view with the fields id
and set
. Because it's a view, most id
s 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?
Upvotes: 0
Views: 51
Reputation: 641
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`
Upvotes: 0
Reputation: 24124
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
Upvotes: 1