删除连接列的重复项

x4shl7ld  于 2021-06-24  发布在  Hive
关注(0)|答案(3)|浏览(328)

我把表a中的数据作为i/p

Col A                      |    Col B    |    Col C
PG_1100000357_1100000356   |  1100000357 |    1100000356 
PG_1100000356_1100000357   |  1100000356 |    1100000357
PG_10909099_12990909       |  10909099   |    12990909
PG_8989898_79797987        |  8989898    |    79797987   
PG_8989898_79797987        |  8989898    |    79797987

我需要写一个查询来接收订单-
1) 当i/p与另一条记录匹配时,从i/p中删除完全相同的副本(示例4和5记录)2)我们需要考虑 COl B , COl C 连接 Col c , Col B 把那个复制品也去掉(第一和第二记录)注:- COl A 是通过联系方式到达的(第二页,b栏,“,”c栏),不用担心

Col A                      |    Col B    |    Col C
PG_1100000357_1100000356   |  1100000357 |    1100000356 
PG_10909099_12990909       |  10909099   |    12990909
PG_8989898_79797987        |  8989898    |    79797987

你能帮帮我吗?非常感谢。

ldxq2e6h

ldxq2e6h1#

下面的sql查询按预期返回结果

;WITH CTE AS( SELECT    ColA, ColB, ColC,  
 ROW_NUMBER() OVER (PARTITION BY CASE WHEN ColB > ColC THEN ColB ELSE ColC END ORDER BY ColB) RN 
 FROM TableA )
 SELECT ColA, ColB, ColC FROM CTE WHERE RN =1
js81xvg6

js81xvg62#

--Oracle SQL: row_number().
--Least and Greatest functions will work regardless Col_B and Col_C have number or varchar2 data type
with s (Col_A, Col_B, Col_C) as (
select 'PG_1100000357_1100000356', 1100000357, 1100000356 from dual union all
select 'PG_1100000356_1100000357', 1100000356, 1100000357 from dual union all
select 'PG_10909099_12990909'    , 10909099  , 12990909   from dual union all
select 'PG_8989898_79797987'     , 8989898   , 79797987   from dual union all
select 'PG_8989898_79797987'     , 8989898   , 79797987   from dual)
select Col_A, Col_B, Col_C
from
   (select s.*,
    row_number () over (partition by least(Col_B, Col_C), greatest(Col_B, Col_C) order by Col_B desc) rn
    from s
   )
where rn = 1;

COL_A                         COL_B      COL_C
------------------------ ---------- ----------
PG_8989898_79797987         8989898   79797987
PG_10909099_12990909       10909099   12990909
PG_1100000357_1100000356 1100000357 1100000356
gjmwrych

gjmwrych3#

在多个列中保存相同的数据是不对的。价值观 Col_B 以及 Col_C 已经存在于 Col_A ,只需将它们拆分,然后使用 least 以及 greatest 功能如@akk0rd87所建议,并考虑到前面的标签 oracle :

with Table_A(Col_A) as 
(
  select 'PG_1100000357_1100000356' from dual union all
  select 'PG_1100000356_1100000357' from dual union all
  select 'PG_10909099_12990909'     from dual union all
  select 'PG_8989898_79797987'      from dual union all
  select 'PG_8989898_79797987'      from dual 
), t as
(
  select regexp_substr(Col_A, '[^_]+', 1, 1) col_one,
         regexp_substr(Col_A, '[^_]+', 1, 2) col_two,
         regexp_substr(Col_A, '[^_]+', 1, 3) col_three
    from Table_A 
)
select max(concat(concat(col_one||'-',least(col_two,col_three)||'-'),
                                      greatest(col_two,col_three)))
       as Col_A,
       least(col_two,col_three) as Col_B, greatest(col_two,col_three) as Col_C
  from t
 group by least(col_two,col_three), greatest(col_two,col_three);

演示

相关问题