基于部分公共字段合并数据

Merging data based on partial common fields

下面是我用来生成所提供输出的查询

SELECT A.MGR_EMP_NBR,E.FIRST_NM || ' ' || E.LAST_NM AS EMP_NM , A.AE_EMP_NBR,a.sales_terr_id, COUNT ( * ) AS pre_leads_total FROM MKVW_ECOMPORTAL_SCHEMA.ECOMWEB_LEADS A    
left join MKVW_MKV_SCHEMA.EMPLOYEE E on A.MGR_EMP_NBR = E.EMP_NBR    
WHERE A.SALES_TERR_ID like '1-2-7-56-%-%-%' AND A.MGR_EMP_NBR is NULL    
GROUP BY A.MGR_EMP_NBR, E.FIRST_NM || ' ' || E.LAST_NM , A.AE_EMP_NBR,a.sales_terr_id

输出-

MGR_EMP_NBR    EMP_NM   AE_EMP_NBR   sales_terr_id      pre_leads_total
                         1234        1-2-7-56-1-1-26    12
                         2311        1-2-7-56-1-1-27    11
                         414         1-2-7-56-1-5-26    10

我想得到值的总和,其中 sales_terr_id 具有前 6 个数字作为共同含义组合 1-2-7-56-1-1-26 and 1-2-7-56-1-1-27 并给出组合 sales_terr_id 作为 1-2-7-56-1-1-0 。 所以在这种情况下,我想获得

的输出

预期输出-

  MGR_EMP_NBR    EMP_NM   AE_EMP_NBR   sales_terr_id      pre_leads_total
                             1234        1-2-7-56-1-1-0    23
                             414         1-2-7-56-1-5-0    10

有可能吗。我不关心AE_EMP_NBR。

如果您想按 sales_terr_id 的前 6 个数字元素进行分组,您可以按其子字符串进行分组;因为它们都是数字,所以您可以使用正则表达式:

with t(MGR_EMP_NBR, EMP_NM, AE_EMP_NBR, sales_terr_id, pre_leads_total) as (
  select null, null, 1234, '1-2-7-56-1-1-26', 12 from dual
  union all select null, null, 2311, '1-2-7-56-1-1-27', 11 from dual
  union all select null, null, 414, '1-2-7-56-1-5-26', 10 from dual
)
select mgr_emp_nbr, emp_nm, min(ae_emp_nbr) as ae_emp_nbr,
  regexp_substr(sales_terr_id, '(\d+-){6}') ||'0' as sales_terr_id,
  sum(pre_leads_total) as pre_leads_total
from t
group by mgr_emp_nbr, emp_nm, regexp_substr(sales_terr_id, '(\d+-){6}');

MGR_EMP_NBR EMP_NM AE_EMP_NBR SALES_TERR_ID    PRE_LEADS_TOTAL
----------- ------ ---------- ---------------- ---------------
                          414 1-2-7-56-1-5-0                10
                         1234 1-2-7-56-1-1-0                23

你必须汇总 ae_emp_nbr 所以我使用了 min() - 你说你不关心那个。

如果您想一次性在现有查询中执行此操作,它将类似于:

select a.mgr_emp_nbr,
  e.first_nm || ' ' || e.last_nm as emp_nm,
  min(a.ae_emp_nbr) as ae_emp_nbr,
  regexp_substr(a.sales_terr_id, '(\d+-){6}') ||'0' as sales_terr_id,
  count (*) as pre_leads_total
from ecomweb_leads a    
left join employee e on a.mgr_emp_nbr = e.emp_nbr    
where a.sales_terr_id like '1-2-7-56-%-%-%'
and a.mgr_emp_nbr is null    
group by a.mgr_emp_nbr, e.first_nm || ' ' || e.last_nm,
  regexp_substr(a.sales_terr_id, '(\d+-){6}')