当公共列具有不同的名称但两个表中的信息相同时,如何连接两个sql表

时间:2013-09-13 19:55:46

标签: sql

SQL查询相对较新。我可以成功地从一个简单的查询中获得结果,该查询显示客户编号和发票总额,将最高美元金额排序到最低。我还要显示客户名称。客户名称[Name]与客户编号一起位于另一个表中,但客户编号的列名称不同,即。 Table 1[Bill-to Customer No_]Table 2仅为[No_]。如何从Table 2获取与客户编号显示在同一行的信息?

3 个答案:

答案 0 :(得分:3)

SELECT 
       [bill-to Customer No_]
       ,customer_name 
FROM table1 AS a 
INNER JOIN table2 AS b on a.[bill-to Customer No_]=b.No_

答案 1 :(得分:1)

select Bill-to, CustomerNo_ ,customer_name 
from Table1 a 
join Table2 b on a.CustomerNo_ = b.No_

答案 2 :(得分:1)

SELECT [Bill-to Customer No_], [Invoice Amount] AS amt, [Name]
FROM Table1 t1 JOIN Table2 t2
ON t1.[Bill-to Customer No_] = t2.[No_]
ORDER BY amt DESC;

我还没有掌握你的专栏名称,但希望你明白这一点。

编辑 :(根据您的新查询)

SELECT [Sell-to Customer No_], [Name], SUM([Amount]) as "Total Dollars Spent" 
FROM [Table 1 - LIVE$Sales Invoice Line] a JOIN [Table 2 - LIVE$Customer] b
ON a.[Sell-to Customer No_] = b.[No_]
WHERE [Source Code] = 'RENTAL' and [Sell-to Customer No_] != 'GOLF' 
GROUP BY [Sell-to Customer No_], [Name]
ORDER BY SUM([Amount]) DESC;

您还需要将[Name]添加到GROUP BY子句中。请注意,SELECT除非GROUP BY正在处理[Amount]等群组功能处理的列,否则SUM()不能{{1}}列。{/ p>