SQL: COUNT() grouped results

家住魔仙堡 提交于 2019-12-12 02:41:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!