Oracle SQL - 比较重复值

时间:2016-10-13 08:42:00

标签: sql oracle duplicates comparison

我有一个字段 RANGE 的表格,其值如下:

102453
104953-256454

值可以是单个6位数字或两个6位数字,用短划线分隔。

用户输入a值(由短划线分隔的6位数字或2位6位数字),并且必须将该值与数据库中的现有值进行比较。

  • 如果输入的值是6位数字,则应将其与数据库中的所有单个6位数值进行比较,并将单独的6位数值存储为由( - )
  • 如果输入的值是两个6位数字,则应对其进行解析,并且每个值必须通过数据库中的每个值进行比较。

我该如何解决?

2 个答案:

答案 0 :(得分:0)

我假设有某种ID字段(我希望)。

with Dumbassery as
(
select id, 'Single' as NumType, substr(MyField,1,6) as Num1, '' as Num2
from MyTable
where length(MyField) = 6
union
select id, 'Range' as NumType, substr(MyField,1,6) as Num1, substr(MyField,8,6) as Num2
from MyTable
where length(MyField) = 13
)

, Filter1 as
(
select id,
       case
           when exists (select 1 from Dumbassery D2 where D1.Num1 between D2.Num1 and D2.Num2 and D2.NumType = 'Range') then 'Exists'
           when exists (select 1 from Dumbassery D2 where D2.NumType = 'Single' and D1.Num1 = D2.Num1) then 'Exists'
           else 'New'
       end as NumExist
from Dumbassery D1
where D1.NumType = 'Single'

union

select id,
       case
           when exists (select 1 from Dumbassery D2 where D1.Num1 between D2.Num1 and D2.Num2 and D2.NumType = 'Range') then 'Exists'
           when exists (select 1 from Dumbassery D2 where D1.Num2 between D2.Num1 and D2.Num2 and D2.NumType = 'Range') then 'Exists'
           when exists (select 1 from Dumbassery D2 where D2.Num2 between D1.Num1 and D1.Num2 and D2.NumType = 'Single') then 'Exists'
           else 'New'
       end as NumExist
from Dumbassery D1
where D1.NumType = 'Range'
)

select distinct *
from Filter1
where NumExist = 'New'

答案 1 :(得分:0)

当您指定范围时,我认为您需要找到具有新范围的交叉点。我添加表 test_val 来检查new_range的一些变体。

 WITH
 table_ranges AS /*is table with ranges*/
 (select '123212' as range from dual union all
  select '123214-223214' as range from dual union all 
  select '123900-987121' as range from dual )
 ,test_val as /*is table with test values*/
 (select '123212' as test_range from dual union all 
  select '123213' as test_range from dual union all 
  select '123215' as test_range from dual union all 
  select '123213-123290' as test_range from dual union all 
  select '124000-125000' as test_range from dual union all 
  select '987000-987124' as test_range from dual union all 
  select '987122-987124' as test_range from dual ) 
  select CAse WHEN EXISTS (select null
                             from table_ranges 
                        where substr(t.test_range,  1,6) between substr(range, 1,6) and substr(range, -6,6) 
                           or substr(t.test_range, -6,6) between substr(range, 1,6) and substr(range, -6,6) ) 
              THEN 'already exists' 
              ELSE'intersection not found' 
            END AS test_status 
   FROM test_val t