第一个表结束时连接两个表

时间:2014-06-06 17:31:57

标签: sql sql-server

我有两张表,比如

tab 1 
Date        Product
29-05-2014  apple
30-05-2014  banana
31-05-2014  pink

tab 2
Date        Product
29-05-2014  red
30-05-2014  blue
31-05-2014  orange
01-06-2014  whit
02-06-2014  black

required table
Date        Product
29-05-2014  apple
30-05-2014  banana
31-05-2014  pink
01-06-2014  whit
02-06-2014  black

第一个表结束时,如何连接两个表?

1 个答案:

答案 0 :(得分:3)

尝试使用COALESCE

SELECT T2.Date,COALESCE(T1.Product,T2.Product) as Product
FROM Tab2 T2 LEFT JOIN
     Tab1 T1 ON T1.Date=T2.Date
如果T1.Product为null,

COALESCE将返回T2.Product。 结果:

DATE        PRODUCT
29-05-2014  apple
30-05-2014  banana
31-05-2014  pink
01-06-2014  whit
02-06-2014  black

结果为SQL Fiddle