Reputation: 3411
I would like to run a query that brings back each record that meets a certain criteria, as well as give me total number of times that occurs in my table.
So if I run:
SELECT id from history where id like "%CLM%";
I get each instance of an id
from my table where "CLM" is somewhere in that id
. What I want in the column NEXT to that is a count of how many times that particular record was found, and I can't seem to figure out how to do that.
What I'm looking for would be something like this:
╔══════╦═══════╗
║ id ║ count ║
╠══════╬═══════╣
║ CLM1 ║ 1 ║
║ CLM2 ║ 5 ║
║ CLM3 ║ 13 ║
╚══════╩═══════╝
I've tried SELECT id, count(id) from history
but it returns this:
╔══════╦══════════╗
║ id ║ count ║
╠══════╬══════════╣
║ ║ 12258432 ║
╚══════╩══════════╝
How do I write this query?
Upvotes: 2
Views: 4582
Reputation: 311348
As you saw, you can use the count
function to count rows. The part you're missing, however, is breaking down this result per id
, which can be done with a group by
clause:
SELECT id, COUNT(*)
FROM history
WHERE id LIKE '%CLM%'
GROUP BY id
Upvotes: 5