SQL Server 2005 - 连接两个表和两个列

SQL Server 2005 - Joining two tables and two columns

在 SQL Server 2005 中,通过在两列上连接两个 table,我们如何通过将第一个 table 两列与第二个 [=29= 匹配来获取值] 两列和非匹配列的值为零?

下面是示例 tables:

Table 1:

City    Vehicle      Count
---------------------------
London  Two wheeler  834
NewYork Four wheeler 60
NewYork Two wheeler  3
Sydney  Four wheeler 514
Sydney  Two wheeler  4551

Table 2:

City    Vehicle     Count
---------------------------
London  Two wheeler   5
NewYork Two wheeler   2
Sydney  Two wheeler  16

预期输出:

City    Vehicle      Count
---------------------------
London  Two wheeler    5
NewYork Four wheeler   0
NewYork Two wheeler    2
Sydney  Four wheeler   0
Sydney  Two wheeler   16

我在 MS Excel 上使用 Pivot Table 公式成功地做到了这一点:

{=INDEX($L:$L0,MATCH(F6,IF($K:$K0=G6,$J:$J0),0))}

你求LEFT JOIN and COALESCE:

SELECT
    t1.city,
    t1.vehicle,
    COALESCE(t2.count,0) as count
FROM
    table_1 t1
LEFT JOIN table_2 t2 ON (t1.city = t2.city AND t1.vehicle = t2.vehicle)