Oracle sql - 如果记录存在则显示其他显示父级

时间:2016-04-14 20:42:42

标签: sql oracle

我想根据以下几种方式将数据分类为:

如果T2中存在值,则显示“A”,否则将“B”显示为“类型”。有没有办法在以下情况下实现或解码?

T1是T2的父母。

T1 
1
2
3
4
5

T2
1
1
3
3
3
4

理想情况下,我的输出是

Type
A
B
A
A
B

编辑:我想补充说A和B是我想根据上述条件显示的文本值,这不是来自db。此外,对于2和2,T2根本没有相应的记录。所以我无法真正检查是否为空。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT T1.Col, 
       CASE WHEN T2.Col IS NOT NULL THEN 'A' ELSE 'B' END AS Type
FROM T1
LEFT JOIN (
   SELECT DISTINCT Col FROM T2
) AS T2 ON T1.Col = T2.Col

答案 1 :(得分:0)

Oracle安装程序

CREATE TABLE T1 ( column_name ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 6;

CREATE TABLE t2 ( column_name ) AS
SELECT 1 FROM DUAL UNION ALL
SELECT 1 FROM DUAL UNION ALL
SELECT 3 FROM DUAL UNION ALL
SELECT 3 FROM DUAL UNION ALL
SELECT 4 FROM DUAL;

<强>查询

SELECT NVL2( T2.column_name, 'A', 'B' ) AS Type
FROM   T1
       LEFT OUTER JOIN
       ( SELECT DISTINCT column_name FROM T2 ) T2
       ON T1.column_name = T2.column_name
ORDER BY T1.column_name;

<强>输出

TYPE
----
A    
B    
A    
A    
B