5

I have two tables with values pertaining to different items like this:

Table1:

ItemID  |  val1  |  val2  |  val3  |
ABC        5        1        2.5
DEF        5        5        3.8
GHI        2        1        4.9
MNO        8        2        1.1
PQR        1        8        2.4

Table 2:

ItemID  |  val4  |  val5  
ABC        hi       4       
DEF        dude     9
GHI        word3    0
JKL        balls    1
MNO        day      5

I would like to join the tables so that they are like this:

ItemID  |  val1  |  val2  |  val3  |  val4  |  val5
ABC        5        1        2.5      hi       4
DEF        5        5        3.8      dude     9
GHI        2        1        4.9      word3    0
JKL        0        0        0        balls    1
MNO        8        2        1.1      day      5
PQR        1        8        2.4      0        0

Where if one table doesn't have the item, it just defaults to zero and adds the column anyway. Is this possible in SQL Server?

4

3 回答 3

6

您可以使用 COALESCE 进行完全外连接:

SELECT COALESCE(TABLE1.ITEMID, TABLE2.ITEMID), COALESCE(VAL1, 0), COALESCE(VAL2, 0), 
    COALESCE(VAL3, 0), COALESCE(VAL4, 0), COALESCE(VAL5, 0)
FROM TABLE1 FULL OUTER JOIN TABLE2 
    ON TABLE1.ITEMID = TABLE2.ITEMID

完全外连接允许您从两个表中获取数据,即使第一个表中没有数据。

于 2013-05-24T18:42:16.837 回答
3
SELECT ISNULL(t1.val1,0), ISNULL(t1.val2,0), ISNULL(t1.val3,0), ISNULL(t2.val4,0), ISNULL(t2.val5,0)  
FROM table1 t1  
FULL OUTER JOIN tale2 t2 ON t1.itemid= t2.itemid
于 2013-05-24T18:53:13.910 回答
1
select a.itemid, isnull(a.val1, 0), isnull(b.val5, 0)
from a 
left join b on a.itemid = b.itemid
于 2013-05-24T18:42:10.650 回答