SQL语句:用count求group by分组的个数
我用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)
select count(*) from #a
或者
select count(*) from (select count(*) num,sid from person group by sid )
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 )
select count(*) from (select count(*) num,sid from person group by sid ) rename
select count(*) from (select sid from person group by sid) s;