标志行具有重复值

时间:2017-11-12 13:45:50

标签: sql oracle

我有查询问题。我有3张桌子。

table A 
    ----------------------------
    NAME   | CODE 
    ----------------------------
    bob    | PL
    david  | AA
    susan  | PL
    joe    | AB
    alfred | PL



table B 
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    PL   | code 1
    PB   | code 2 
    PC   | code 3

table C 
    ----------------------------
    CODE | DESCRIPTION
    ----------------------------
    AA   | code 4
    AB   | code 5 
    AC   | code 6

表B和C具有唯一的行。 结果我需要标记哪一行有重复记录:

    -------------------------------------
    NAME   | CODE | DESCRIPTION | DUPLICATE
    -------------------------------------
    bob    | PL   | code 1      | YES
    david  | AA   | code 4      | NO
    susan  | PL   | code 1      | YES
    joe    | AB   | code 5      | NO
    Alfred | PL   | code 1      | YES

到目前为止我尝试了什么

http://sqlfiddle.com/#!9/ffb2eb/16

2 个答案:

答案 0 :(得分:3)

我不明白为什么你需要表BC来计算标志。您可以使用窗口函数执行此操作:

select a.*,
       (case when count(*) over (partition by a.code) > 1 then 'YES' else 'NO'
        end) as flag
from a;

如果您想引入其他值,则需要BC

select a.*, coalesce(b.description, c.description) as description,
       (case when count(*) over (partition by a.code) > 1 then 'YES' else 'NO'
        end) as flag
from a left join
     b
     on a.code = b.code left join
     c
     on a.code = c.code;

这是一个有效的 Oracle SQL Fiddle

答案 1 :(得分:1)

在MYSQL(http://sqlfiddle.com/#!9/9a149b/1

中尝试以下代码

注意: - 代码也适用于Oracle http://sqlfiddle.com/#!4/6c6df/5

select A.*, 
COALESCE(B.DESCRIPTION, C.DESCRIPTION) AS DESCRIPTION,
 dup.DUPLICATE
 from A 
left join B on A.CODE = B.CODE
left join C on A.CODE = C.CODE
INNER JOIN (select a.code,
        case when count(a.code) > 1 then 'YES' else 'NO' end as 
        DUPLICATE 
        from A 
        group by a.code) dup
        ON A.code=dup.code