2014-01-09 46 views
0

這裏是我的數據:如何獲取查詢以返回其中一行的前三個字符與另一行匹配的行?

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
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 
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) 
) 
1
 select res from (select res,count(*) over 
    (partition by substr(res,1,3) order by null) cn from table_name) where cn>1; 
+0

http://sqlfiddle.com/#!4/3e0091/5 – Sai

相關問題