2016-10-04 92 views
0

在SQL Server 2005中,通过在两列上连接两个表,我们如何通过将第一个表的两列匹配到第二个表的两列来获取值,匹配列?SQL Server 2005--连接两个表和两列

以下是在示例表:

表1:

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

表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 

我这样做成功上使用Pivot的MS Excel表公式:

{=INDEX($L$6:$L$550,MATCH(F6,IF($K$6:$K$550=G6,$J$6:$J$550),0))} 
+0

你问如何写一个'SELECT'声明?你有没有尝试过或要求提供代码? –

回答

1

您寻求LEFT JOINCOALESCE

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)