sql - 非聚合查询内部的聚合情况

标签 sql amazon-redshift

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

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

我需要再添加一个条件,让我计算每个代表的申请日期非空的用户数(例如:代表 1 有 3 个已填写申请日期的用户),并将其分配到类别(因为有 3 个用户,代表是一个某些状态类别)。这看起来像这样:

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

您能否协助将我的查询添加到各个代表而不是整体?非常感激!

最佳答案

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

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;

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

关于sql - 非聚合查询内部的聚合情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48574032/

相关文章:

sql - 与前 24 小时的计数日差

sql - redshift-如何插入表格生成的时间序列

AS附近的mySQL错误

mysql - 如何使用mysql替换字符串的一部分

csv - 根据以下逻辑加载数据

Redshift中的Python UDF函数总是返回NULL值

python - 使用 Psycopg2 从 Redshift 写入文件抛出异常

sql - 如何将 postgresql 数据库模式导出为 XML 格式?

java - 如何将序列值视为生成的键?

sql - 选择具有满足某些约束的多个子关系的所有行