我有3个表格,结构如下。
表 - 1
Cust_ID
Order_Date
Order_time
Cust_Name
Cust_Address
Order_Status
Emp_ID
Cust_Prod_Cost
Cust_Balance
表 - 2
Cust_ID
Delivered_Time
Delivered_Qty
Payment_Type
Cust_Prod_Cost
Cust_Balance
Amount_Paid
Order_Status
Emp_ID
WHID
表 - 3
Cust_ID
Order_Date
Order_time
Delivery_Time
Cust_Prod_Cost
Delivered_Qty
Payment_Type
Amt_To_Pay
Amount_Paid
Due_Amount
Order_Status
Emp_ID
WHID
现在,当Table2-Cust_ID = Table1.Cust_ID和Table2.Order_Status ='0'时,我想将表-1和表2中的数据合并到表-3中。
你能帮我解决一下SQL Server查询吗?我尝试了很多方法,但没有结果
答案 0 :(得分:0)
Insert Into Table3
(
Cust_ID
Order_Date
Order_time
Delivery_Time
Cust_Prod_Cost
Delivered_Qty
Payment_Type
Amt_To_Pay
Amount_Paid
Due_Amount
Order_Status
Emp_ID
WHID
)
Select t1.Cust_Id,
t1.Order_Date,
t1.Order_Time,
t2.Delivered_Time,
t2.Cust_Prod_Cost,
t2.Delivered_Qty,
t2.Payment_Type,
Amt_To_Pay (doesn't exist in t1 or t2),
t2.Amount_Paid,
Due_Amount (doesn't exist in t1 or t2),
t1.Order_Status,
t1.Emp_ID,
t1.WHID
From Table1 t1
Inner Join Table2 t2 On t2.Cust_Id = t1.Cust_Id
And t2.Order_Status = '0'
答案 1 :(得分:0)
SELECT
A.Cust_ID,Order_Date,Order_time,Delivery_Time,Cust_Prod_Cost,
Delivered_Qty,Payment_Type,Amt_To_Pay,Amount_Paid,
Due_Amount,Order_Status,A.Emp_ID,WHID
FROM TABLE1 A
JOIN TABLE2 B ON A.Cust_ID=B.Cust_ID AND B.Order_Status=0
答案 2 :(得分:0)
尝试以下sql:
INSERT INTO Table3 (
Cust_ID
,Order_Date
,Order_time
,Delivery_Time
,Cust_Prod_Cost
,Delivered_Qty, Payment_Type
,Amt_To_Pay, Amount_Paid
,Due_Amount
,Order_Status
,Emp_ID
,WHID
)
SELECT t1.Cust_ID
,t1.Order_Date
,t1.Order_time
,t2.Delivered_Time
,t2.Cust_Prod_Cost
,t2.Delivered_Qty
,t2.Payment_Type
,NULL AS Amount_To_Pay
,t2.Amount_Paid
,NULL AS Due_Amount
,t2.Due_Amount
,t2.WHID
FORM Table1 t1 LEFT JOIN t2 ON t1.Cust_ID = t2.Cust_ID
WHERE t2.Order_Status = 0
将NULL
替换为有效值