假如有数据:
1.单个字段分组
— 根据 user_name 分组
select user_name from T_JASON_TEST group by user_name;
— 根据 telphone分组
select telphone from T_JASON_TEST group by telphone;
结果如下,左是 user_name,右是telphone :
2.多个字段分组
— 根据 user_name 和 telphone 分组
select user_name,telphone from T_JASON_TEST group by user_name,telphone;
— 这个分组效果等同于distinct 函数,起到去重的效果
select distinct user_name,telphone from T_JASON_TEST;
— 根据 user_name,telphone,result 三个字段分组
select user_name,telphone,result from T_JASON_TEST group by user_name,telphone,result;
— 效果等同于distinct ,去重
select distinct user_name,telphone,result from T_JASON_TEST;
注意:多个字段分组或者单个字段分组,select 后面所要查询的字段必须是分组字段,否则报错,
select user_name,telphone from T_JASON_TEST group by user_name; — 报错:ORA-00979: 不是 GROUP BY 表达式
— 但是下面这样是可以的,即只查询出分组字段中的其中一个或多个字段
select user_name from T_JASON_TEST group by user_name,telphone ;
— 或者结合分组函数使用也是可以的。
3.分组函数
— 单个字段分组,使用求和函数sum 。查询每个人的通话时长
select user_name , sum(time_long) from T_JASON_TEST group by user_name; –结果如图1
— 多个字段分组,使用求和函数sum 。查询每个人对每个电话的通话时长
select user_name , sum(time_long) from T_JASON_TEST group by user_name,telphone; –结果如图2
— 或者如下(分组效果等同于)
select user_name,telphone, sum(time_long) from T_JASON_TEST group by user_name,telphone; –结果如图3
-
— 分组和min()求最小值函数使用
-
select user_name, min(time_long) from T_JASON_TEST group by user_name; –结果如图4
转自:https://blog.csdn.net/whxjason/article/details/107677512