一尘不染

在非聚合查询中时的聚合情况

sql

我有一个非常庞大的查询,其最简单的形式如下所示:

select r.rep_id, u.user_id, u.signup_date, pi.application_date, pi.management_date, aum
from table1 r
left join table2 u on r.user_id=u.user_id
left join table3 pi on u.user_id=pi.user_id

我需要再添加一个条件,该条件可以让我获得每个代表的应用程序日期不为空的用户数(例如:rep
1具有3个用户的应用程序日期已填写),并将其分配给类别(由于3个用户,rep是某个状态类别)。看起来像这样:

case when sum(case when application_date is not null then 1 else 0 end) >=10 then 'status1'
   when sum(case when application_date is not null then 1 else 0 end) >=5 then 'status2'
   when sum(case when application_date is not null then 1 else 0 end) >=1  then 'status3'
   else 'no_status' end as category

但是,如果我只是将其添加到select语句中,则所有代表将变为status1,因为sum()是在所有使用申请日期的顾问程序上完成的:

select r.rep_id, u.user_id, u.signup_date, pi.application_date, pi.management_date, aum,
(
 select case when sum(case when application_date is not null then 1 else 0 end) >=10 then 'status1'
   when sum(case when application_date is not null then 1 else 0 end) >=5 then 'status2'
   when sum(case when application_date is not null then 1 else 0 end) >=1  then 'status3'
   else 'no_status' end as category
from table3
) as category
from table1 r
left join table2 u on r.user_id=u.user_id
left join table3 pi on u.user_id=pi.user_id

您能协助我的查询遍及销售代表而不是整体吗?非常感激!


阅读 283

收藏
2021-03-08

共1个答案

一尘不染

根据您的描述,我认为您需要一个窗口函数:

select r.rep_id, u.user_id, u.signup_date, pi.application_date, pi.management_date, aum,
       count(pi.application_date) over (partition by r.rep_id) as newcol
from table1 r left join
     table2 u
     on r.user_id = u.user_id left join
     table3 pi
     on u.user_id = pi.user_id;

如果您愿意,可以使用count()中的case获取范围。

2021-03-08