SQL语句:用count求group by分组的个数

如person表 pid,sid 两字段
我用sid分组,SQL语句如下:
select count(*) num,sid from person group by sid
结果如下:
num sid
5 001
10 002
12 003
0 004

我想要条SQL语句求共分有几组,如上结果是4组,应该怎么写?

1、创建测试表,create table test_group(pid number, sid varchar2(20));

2、插入测试数据,

insert into test_group values(1,'001');

insert into test_group values(2,'001');

insert into test_group values(2,'002');

insert into test_group values(2,'002');

insert into test_group values(2,'002');

insert into test_group values(3,'003');

insert into test_group values(3,'003');

insert into test_group values(null,'004');

3、查询表中记录,select t.*, rowid from test_group t;

4、编写sql,将记录分组后,记录组数,结果为4组,

select count(*) from (select count(*) num,sid from test_group group by sid)

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-12-15
select count(*) num,sid into #a from person group by sid
select count(*) from #a

或者
select count(*) from (select count(*) num,sid from person group by sid )本回答被提问者采纳
第2个回答  2018-01-09
from括号后面要带重命名
select count(*) from (select count(*) num,sid from person group by sid ) rename
第3个回答  2017-12-14
select count(*) from (select sid from person group by sid) s;

相似回答