从3个单独的表插入表中

时间:2018-08-08 00:00:04

标签: sql-server

我的脸被踢了。...

我总共有4张桌子
1.业务(BusinessID,CustomerID,BusName,地区)
2.客户(客户ID,姓名)
3.销售(BusinessID,CustomerID,地区,1月,2月,3月,4月,5月,6月)
4.性能(这是我要输入信息的表)

我已经创建了具有以下几列的表格:BusinessID,CustomerID,BusName,Name,Territory,Jan,Feb,Mar,Apr,May,Jun

每次尝试插入不正确的连接时,都会出现一堆错误“无法绑定多部分标识符”

insert into Performance (BusinessID, CustomerID, BusName, Name, Territory, January2018, February2018, March2018, April2018, May2018, June2018)
select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID; 

由于此错误,我不得不将3个单独的插入进去,这导致了一堆null。...

掌心正在发生,可以使用一些建议。

图片:enter image description here

谢谢, VeryNew2SQL

2 个答案:

答案 0 :(得分:2)

您已经使用了表别名,因此必须在SELECT中使用这些别名

A代表BusinessB代表CustomerC代表Sales。 阅读有关别名here的信息。

select A.BusinessID, B.CustomerID, A.BusName, B.Name, C.Territory, C.January2018, C.February2018, C.March2018, C.April2018, C.May2018, C.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID; 

答案 1 :(得分:0)

FROMJOIN子句中创建表别名时,需要引用SELECT语句中的别名,而不是实际的表名。

或者,保留您的SELECT语句不变,并调整表名以删除别名。然后,您将需要连接条件来引用您的实际表名,而不是别名。例如,

select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business
inner join Customer ON Business.CustomerID = Customer.CustomerID
inner join Sales  ON Customer.CustomerID = Sales.CustomerID; 

即使只是尝试先运行上面的SELECT语句,也可以确保在插入之前尝试查询之前正确无误。