将重叠值标记为两列

时间:2016-10-28 07:30:35

标签: sql teradata

我有以下数据快照:

ID  NUM1    NUM2
1   1000    1001
2   1002    1003
3   1001    1004
4   1003    1006
5   1007    1008

我想标记NUM1和NUM2列中包含值的行:

我想要的输出是:

ID  NUM1    NUM2    Flag
1   1000    1001    Y
2   1002    1003    Y
3   1001    1004    Y
4   1003    1006    Y
5   1007    1008    
你能帮帮我吗?感谢

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT id,num1,num2,exists
(
SELECT 1
FROM yourtable 
WHERE num1 IN (SELECT num2 from yourtable)
OR num2 IN (SELECT num1 from yourtable)
) as flag
FROM yourtable

输出应如下所示:

ID  NUM1    NUM2    Flag
1   1000    1001    TRUE
2   1002    1003    TRUE
3   1001    1004    TRUE
4   1003    1006    TRUE
5   1007    1008    FALSE

答案 1 :(得分:0)

只需在选择列表中执行EXISTS,以验证表格的其他列中是否存在NUM1和NUM2中的至少一个:

SELECT t1.id, t1.num1, t1.num2,
       exists (select 1 from tablename t2
               where t2.num2 = t1.num1
                  or t2.num1 = t1.num2) as Flag

FROM tablename t1

或者,自我LEFT JOIN

select distinct t1.*, case when t2.id is not null then 'Y' else 'F' end as flag
from tablename t1
left join tablename t2 on t2.num2 = t1.num1 or t2.num1 = t1.num2

执行select distinct以避免重复!