巧用having by

Posted dlp-527

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了巧用having by相关的知识,希望对你有一定的参考价值。

mysql学习教程参考:https://www.w3school.com.cn/sql/index.asp
where 与 having by实例运用参考:https://www.2cto.com/database/201712/706595.html
 
 
--可选认证中至少有一项通过的用户占比,直接计算
select
 count(distinct case when c.auth_type=‘可选‘ and c.auth_status in (‘已认证‘, ‘已过期‘) then c.user_id end) as pass_cnt
,count(distinct c.user_id) as tot_cnt
,count(distinct case when c.auth_type=‘可选‘ and c.auth_status in (‘已认证‘, ‘已过期‘) then c.user_id end)/count(distinct c.user_id) per_cnt
from(
 select a.*,ath.auth_item,ath.auth_type,ath.auth_status,ath.auth_suc_time
  from(
   select laf.user_id,laf.main_order_id,laf.loan_apply_submit_time
   from pl_performance_loan_apply_fact laf
   left join pl_customer_basic_info usb on laf.user_id=usb.user_id
   where laf.reborrow_status = ‘首借‘ and usb.merchant_no=‘DuitSayang‘
      and date(laf.loan_apply_submit_time)>=‘2019-08-03‘ and date(laf.loan_apply_submit_time)<=‘2019-08-05‘
) a
left join pl_customer_auth_info ath on a.user_id = ath.user_id
) c
;
 
 
--找出未通过认证的用户,巧用having by
select a.user_id,a.phone
  from(
   select laf.user_id,laf.main_order_id,laf.loan_apply_submit_time,usb.phone
   from pl_performance_loan_apply_fact laf
   left join pl_customer_basic_info usb on laf.user_id=usb.user_id
   where laf.reborrow_status = ‘首借‘ and usb.merchant_no=‘DuitSayang‘
      and date(laf.loan_apply_submit_time)>=‘2019-08-03‘ and date(laf.loan_apply_submit_time)<=‘2019-08-05‘
) a
left join pl_customer_auth_info ath on a.user_id = ath.user_id
group by a.user_id,a.phone
having max( case when ath.auth_type=‘可选‘ and ath.auth_status in (‘已认证‘, ‘已过期‘) then 1 else 0 end) = 0
 

以上是关于巧用having by的主要内容,如果未能解决你的问题,请参考以下文章

Linq to SQL -- Group ByHaving和ExistsInAnyAllContains

巧用having by

PostgreSQL HAVING 子句

PostgreSQL HAVING 子句

WHEREORDER BYGROUP BYHAVING语句解析

order bygroup byhaving的区别