问题
this is my current query:
SELECT locationname, eventid
FROM events
GROUP BY locationname
ORDER BY locationname ASC
As you can see it's grouped by locationname because there are several rows with the same locationname.
In the output i just need a list of "distinct" (grouped) locations but behind every location there should be the total amount of each location.
So if in "events" are 4 locationsname with "Congress Center NYC" the output should be "Congress Center NYC (4)".
Is there a way to expand the query with a COUNT()?
Thanks!
回答1:
This is a straightforward aggregate query.
SELECT locationname, COUNT(*) number
FROM events
GROUP BY locationname
ORDER BY locationname
If you want specific formatting, you can get it using this first line of your query.
SELECT CONCAT(locationname, ' (', COUNT(*), ')')
回答2:
Selecting COUNT(locationname) should do what you want. I.e.
SELECT locationname, COUNT(locationname)
FROM events
GROUP BY locationname
ORDER BY locationname ASC
回答3:
In your query example there is "event_id", when you add grouping you will receive "event_id" of the first occurred row with the same "locationame", you can use group_concat to get all events and perform count in the same time
SELECT locationname, group_concat(eventid), count(eventid) as number
FROM events
GROUP BY locationname
ORDER BY locationname ASC
also you can use concat function to have the output exactly as you wrote
SELECT concat(locationname, ' (', count(*), ')')
FROM events
GROUP BY locationname
ORDER BY locationname ASC
来源:https://stackoverflow.com/questions/40577159/sql-count-grouped-results