Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

Group by aggregate function SQL

I need to group by an aggregated by count column and it's not possible on SQL. As a simple example, I have a table with events and I want to group by the count of those events.

Table (event 1,event 2,event 2,event 3,event 3,event 4)

select events, count (events) 
from table 
group by events

the result is

events   count(events)
event 1  1
event 2  2
event 3  2
event 4  1

What I need is to know how many events occurred 1 time and how many 2 times and so on, which would give me the following result:

count(events) occurences
1             2
2             2

Can anyone suggest a way to obtain that result, please?

Thanks in advance!

question from:https://stackoverflow.com/questions/65905477/group-by-aggregate-function-sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

here is one way you can do it:

select 
   e.counts
 , count(*) occurences 
from (
select events, count (events) counts
from table 
group by events
) e
group by e.counts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...