如何获取查询以返回一行中前三个字符与另一行匹配的行?

时间:2014-01-09 00:15:02

标签: sql oracle oracle11g

这是我的数据:

with first_three as 
    (
    select 'AAAA' as code  from dual union all
    select 'BBBA' as code  from dual union all
    select 'BBBB' as code  from dual union all
    select 'BBBC' as code  from dual union all
    select 'CCCC' as code  from dual union all
    select 'CCCD' as code  from dual union all
    select 'FFFF' as code  from dual union all
    select 'GFFF' as code  from dual )
    select substr(code,1,3) as r1 
    from first_three
    group by  substr(code,1,3)
    having count(*) >1 

此查询返回符合cirteria的字符。现在,我如何从中选择以获得所需的结果?或者,还有另一种方式吗?

期望的结果

BBBA
BBBB
BBBC
CCCC
CCCD

3 个答案:

答案 0 :(得分:3)

WITH code_frequency AS (
  SELECT code,
         COUNT(1) OVER ( PARTITION BY SUBSTR( code, 1, 3 ) ) AS frequency
  FROM   table_name
)
SELECT code
FROM   code_frequency
WHERE  frequency > 1

答案 1 :(得分:2)

WITH first_three AS (
  ...
) 
SELECT * 
FROM first_three f1
WHERE EXISTS (
    SELECT 1 FROM first_three f2 
    WHERE f1.code != f2.code 
        AND substr(f1.code, 1, 3) = substr(f2.code, 1, 3)
)

答案 2 :(得分:1)

     select res from (select res,count(*) over 
    (partition by substr(res,1,3) order by null) cn from table_name) where cn>1;