sql - 使用列表聚合的 group by 问题
问题描述
在一个查询中,listagg()
我试图为 split_rep:existence of user_id
that has添加一个子句profile_type='Split'
,而对于 multi_rep:existence of user_id
with more than one ap.id
。
简化查询(其中 -- 是我想要做的):
select distinct r.user_id,
listagg(distinct ap.rep_code, ', ') within group (order by ap.bill_rate) as rep_code_list
--,case when max(ap.profile_type) over (partition by r.user_id)='Split' then 1 else 0 end has_split_rep_code
--,case when count(ap.id) over (partition by r.user_id)>1 then 1 else 0 end has_multi_rep_code
from representatives r
join profiles ap on r.user_id=ap.user_id
group by r.user_id
这会引发一个需要出现profile_type
的错误- 但是如果添加,则会给出错误的输出。不知道为什么 listagg 不支持窗口函数,但知道如何绕过它吗?id
group by
样本数据:
user_id id profile_type rep_code
A A Self AAA
A B Self AAB
B C Self AAC
C D Self AAD
C E Split AAE
D F Split AAF
期望的输出:
user_id rep_code split_rep_code multi_rep_code
A AAA, AAB 0 1
B AAC 0 0
C AAD, AAE 1 1
D AAF 1 0
解决方案
你可以使用OVER
:
select distinct r.user_id,
listagg(distinct ap.rep_code, ', ') within group (order by ap.bill_rate)
over(partition by ap.user_id) as rep_code_list
-- rest of cols
from representatives r
join profiles ap on r.user_id=ap.user_id;
推荐阅读
- python - Python:加载txt文件并形成数据框
- node.js - 实体管理器和存储库 typeorm 之间的区别
- javascript - 我将如何用 Jquery 或 javascript 重新编写这个 css?
- html - 使前 2 个标题变粘
- javascript - Vue.js 组件仅在浏览器页面刷新后更新
- ios - “使用 Bitcode 重建”和可选依赖项
- elasticsearch - 将 url 标记为已死。最后一个错误:HostUnreachableError
- concurrency - 我收到“来自 NNN-USD 的未定义汇率”
- c# - 在生产环境中使用 Fluent Asserts 增强默认的 .NET LINQ 不良异常?
- oauth-2.0 - 如何使用 Keycloak Server 内省来自公共客户端的 access_token?