在Oracle SQL中合并具有相同ID但不同列值的行

时间:2019-04-04 19:48:03

标签: sql oracle group-by

我正在尝试根据具有不同列值的ID号将行合并为一个。在此示例中,我将基于Case语句创建新的列值。请在下面查看我的代码以及实际结果与预期。非常感谢您的帮助。

SELECT *

FROM (
SELECT CTR_NMBR, CODE, EXEC_ID,

CASE
  WHEN CODE = '2_EXEC_ZERO'
  THEN 2
  Else NULL
END AS Exclude_Zero,

CASE
  WHEN CODE = '3_EXEC_MAT'
  THEN 3
  Else NULL
END AS Exclude_Mat

FROM EXCLUDED)

WHERE COALESCE(Exclude_Zero, Exclude_Mat) IS NOT NULL;

实际结果:

CTR_NMBR        CODE            EXEC_ID         Exclude_Zero        Exclude_Mat 
E0105753       2_EXEC_ZERO       565                2
E0105753       3_EXEC_MAT        565                                    3

预期结果:

CTR_NMBR        EXEC_ID         Exclude_Zero        Exclude_Mat
E0105753         565                2                    3

3 个答案:

答案 0 :(得分:2)

我认为您想要汇总:

SELECT CTR_NMBR, EXEC_ID,
       MAX(CASE WHEN CODE = '2_EXEC_ZERO' THEN 2
           END) AS Exclude_Zero,
       MAX(CASE WHEN CODE = '3_EXEC_MAT' THEN 3
           END) AS Exclude_Mat
FROM EXCLUDED
GROUP BY CTR_NMBR, EXEC_ID;

答案 1 :(得分:1)

从选择中删除code并进行条件汇总

SELECT CTR_NMBR, EXEC_ID,

 max(CASE
  WHEN CODE = '2_EXEC_ZERO'
  THEN 2 end)      
 AS Exclude_Zero,

 max( CASE
  WHEN CODE = '3_EXEC_MAT'
  THEN 3 end) AS Exclude_Mat

FROM EXCLUDED group by CTR_NMBR, EXEC_ID

答案 2 :(得分:1)

您可以将decodeaggregation一起使用,regex可以从code列中动态提取数字

with excluded(ctr_nmbr, code, exec_id ) as
(
 select 'E0105753', '2_EXEC_ZERO', 565 from dual union all
 select 'E0105753',  '3_EXEC_MAT', 565 from dual   
)
select ctr_nmbr, exec_id,
       max(decode(code,'2_EXEC_ZERO',regexp_substr(code,'[^_]+',1),null)) as Exclude_Zero,
       max(decode(code,'3_EXEC_MAT',regexp_substr(code,'[^_]+',1),null)) as Exclude_Mat           
  from excluded
 group by ctr_nmbr, exec_id;

Demo