我正在寻求一些帮助来构建一个SQL以获得某些结果。 以下是两个表格。
表1
Col1 | Col2 | Col3 | Col4 ---------------------------------------- TESTPC01 | 14/08/2014 | ABCD | CXYZ TESTPC02 | 14/08/2014 | EFGH | IJKL
表2
COl1 | Col2 | Col3 | Col4 ---------------------------------------- TESTPC01 | 14/08/2014 | ENT | DOC
RESULT
COl1 | Col2 | Col3 | Col4 | Col5 | Col6 ------------------------------------------------------- TESTPC01 | 14/08/2014 | ENT | DOC | ABCD | YES | TESTPC02 | 14/08/2014 | EFGH | NULL | NULL | NO |
仅当表2中列出了该特定Col3值的数据时,才会显示该特定匹配的Table1.Col1 = Table2.Col1。
如果上述条件失败则NO
我可以使用简单的select语句构建SQL,但无法动态创建col6。 任何人都可以指导我如何实现这个目标吗?
答案 0 :(得分:0)
您希望left outer join
具有条件表达式:
select t2.col1, t2.col2, t2.col3,
(case when t1.col1 is not null then t2.col4 end) as col4
t1.col3 as col5,
(case when t1.col1 is null then 'Yes' else 'No' end) as col6
from table2 t2 left join
table1 t1
on t2.col1 = t1.col1 and t2.col2 = t1.col1;
我不清楚为什么col4
在没有匹配时会NULL
。通常,您将保留第一个表中的所有值。但是,这就是您指定结果的方式。