我需要将第一个ib_data故障排除列与下一个ib_data之间的所有ob_data进行汇总。
select *,
rank()OVER (PARTITION BY service_request_number ORDER BY (activity_created_date::timestamp) asc) AS flag,
case when activity_type ~* '(Inbound|Transfer Accepted|Chat|Dell Service Provider|fax|social)'::text then 'ib_data'
else 'ob_data'
end as activity_type_flag
from log_activity_view
where service_request_number='984213950'
此处,st = service_tag,srn = service_request_number,ai = activity_id,acd = activity_created_date,atype = activity_type,atf = activity_type_flag 现在的输出是:
st srn ai acd atype troubleshooting flag atf
1 2 a 2018-12-21 ib ab 1 ib_data
1 2 b 2018-12-22 ob pq 2 ob_data
1 2 c 2019-01-21 ib xt 3 ib_data
我想要输出为
st srn ai acd atype troubleshooting flag atf
1 2 a 2018-12-21 ib ab,pq 1 ib_data
答案 0 :(得分:0)
我不确定是否能解决您的全部问题。但是我了解的是:您想聚合两个troubleshooting
之间的所有atf = ibdata
值。
您需要按atf
创建组。可以这样做:
-- first step, create summable column
SELECT
*,
CASE WHEN atype = 'ib' THEN 1 ELSE 0 END
FROM
troubles
这会在您的行中添加一个列,其值为1,0,1
。
这可以与累积SUM窗口功能结合使用:
-- second step, cumulative sum
SELECT
*,
SUM(CASE WHEN atype = 'ib' THEN 1 ELSE 0 END) OVER (ORDER BY acd)
FROM
troubles
这将产生值(1,1,2)
。您会看到,现在您有了分组的条件。每个ib_data
值都会增加一个新的组值。
现在,您只需要按此新列进行分组:
SELECT
MIN(st) as st, MIN(srn) as srn, MIN(ai) as ai,
MIN(acd) as acd, MIN(atype) as atype,
array_agg(trouble ORDER BY acd) as trouble, -- your aggregation
MIN(flag) as flag, MIN(atf) as atf
FROM
(
SELECT
*,
SUM(CASE WHEN atype = 'ib' THEN 1 ELSE 0 END) OVER (ORDER BY acd)
FROM
troubles
) s
GROUP BY sum
重要的是array_agg
(当然,您可以将其转换为文本。)。因为您没有定义其他列应该发生的情况,所以为简单起见,我假定它们应该是最小的。 (当然,您可以使用first_value窗口函数或其他方法执行此操作)