今天这个帖子是为了更加熟悉 sql group by的运用:
1、select 后面跟的字段和group by的筛选字段之间关系;
2、如果select 后面字段没有数字项怎么用group by;
3、使用group by 和 where的先后关系;
譬如有这样一个表:
create table table_1(column_a varchar2(10),column_b varchar2(10),column_c int);
insert into table_1 values('a','b',1);
insert into table_1 values('a','b',2);
insert into table_1 values('a','b',3);
insert into table_1 values('a','b',3);
1、select 除聚合项以外的字段必须出现在group by后面。
譬如,
select column_a,column_b,sum(column_c) from table_1 group by column_a;
这个就肯定出错。
ORA-00979: not a GROUP BY expression
select column_a,column_b,sum(column_c) from table_1 group by column_a,column_b;
这个就肯定可以。
2、如果没有sum/average/max等聚合,或者说被筛选项并非数字类型时,group by作用就是去重。
select column_a,column_b,column_c from table_1 group by column_a,column_b,column_c;
这段group by就是a/b/c三列组合去重。这里显然,a/b两列是为了筛选出C。也就是说a和b确认情况下,只能取一个C。
这种写法,相当于:
select distinct column_a,column_b,column_c from table_1;
--注意,这里distinct一定要写在所有字段前面,不可以select column_a,distinct column_b...
3、group by和where先后顺序:一定是先where 后 group by。也就是只在符合规定条件内的记录集做聚合/去重。
select column_a,column_b,column_c from table_1
group by column_a,column_b,column_c
where rownum<3 and column_a='a'
;
ORA-00933: SQL command not properly ended
select column_a,column_b,column_c from table_1
where rownum<3 and column_a=‘a’
group by column_a,column_b,column_c;