【PostGreSql】SQL中只要用到聚合函数就一定要用到group by 吗?

一,问题:

select 
aa.apply_time, 
aa.product_cid, 
count(case  when  aa.r_state='审核中'   then apply_id end  )审核中订单数,
count(case  when  aa.r_state LIKE '拒绝'   then apply_id end  )拒绝订单数 
from view_test_sys_apply_standard_tri_flow_temp aa GROUP BY 1
> ERROR:  column "aa.product_cid" must appear in the GROUP BY clause or be used in an aggregate function
LINE 3: aa.product_cid, 
        ^

> 时间: 0.012s

使用group by时上报:

ERROR:  column "aa.product_cid" must appear in the GROUP BY clause or be used in an aggregate function

意思是aa.product_cid字段必须在GROUP BY中出现或者被用于聚合函数

二,解答:

看情况

1、当聚集函数和非聚集函数出现在一起时,需要将非聚集函数进行group by
2、当只做聚集函数查询时候,就不需要进行分组了。

 

三,实例:

1,当聚集函数和非聚集函数出现在一起时,需要将非聚集函数进行group by

select 
aa.apply_time, 
aa.product_cid, 
count(case  when  aa.r_state='审核中'   then apply_id end  )审核中订单数,
count(case  when  aa.r_state LIKE '拒绝'   then apply_id end  )拒绝订单数 
from view_test_sys_apply_standard_tri_flow_temp aa GROUP BY 1,2

【PostGreSql】SQL中只要用到聚合函数就一定要用到group by 吗?_第1张图片

 

2,当只做聚集函数查询时候,就不需要进行分组了

select 
count(case  when  aa.r_state='审核中'   then apply_id end  )审核中订单数,
count(case  when  aa.r_state LIKE '拒绝'   then apply_id end  )拒绝订单数 
from view_test_sys_apply_standard_tri_flow_temp aa 

【PostGreSql】SQL中只要用到聚合函数就一定要用到group by 吗?_第2张图片

 

3,当聚集函数和非聚集函数出现在一起时,将非聚集函数不进行group by

select 
aa.apply_time, 
aa.product_cid, 
count(case  when  aa.r_state='审核中'   then apply_id end  )审核中订单数,
count(case  when  aa.r_state LIKE '拒绝'   then apply_id end  )拒绝订单数 
from view_test_sys_apply_standard_tri_flow_temp aa 

【PostGreSql】SQL中只要用到聚合函数就一定要用到group by 吗?_第3张图片

 

第一个非聚合函数使用group by,而第二个非聚合函数不适用group by时也是会上报错误;

select 
aa.apply_time, 
aa.product_cid, 
count(case  when  aa.r_state='审核中'   then apply_id end  )审核中订单数,
count(case  when  aa.r_state LIKE '拒绝'   then apply_id end  )拒绝订单数 
from view_test_sys_apply_standard_tri_flow_temp aa GROUP BY 1

【PostGreSql】SQL中只要用到聚合函数就一定要用到group by 吗?_第4张图片

你可能感兴趣的:(PostGreSql,group,by)