[英]How to get column from another table and insert into other table?
我有兩個表Cal_date
和RPT_Invoice_Shipped
。
表cal_data
具有列
month_no
start_date
end_date
RPT_Invoice_Shipped
表具有列
Day_No
Date
Div_code
Total_Invoiced
Shipped_Value
Line_Shipped
Unit_Shipped
Transaction_Date
我正在使用下面的插入語句在RPT_Invoice_Shipped
表中插入數據。
insert into [Global_Report_Staging].[dbo].[RPT_Invoice_Shipped]
(Day_No, Date, Div_code, Total_Invoiced, Transaction_Date)
select , CONVERT(DATE,Getdate()) as Date, LTRIM(RTRIM(div_Code)),
sum(tot_Net_Amt) as Total_Invoiced, (dateadd(day, -1, convert(date, getdate())))
from [Global_Report_Staging].[dbo].[STG_Shipped_Invoiced]
WHERE CONVERT(DATE,Created_date )=CONVERT(DATE,Getdate())
group by div_code
在RPT_Invoice_Shipped
表的Day_No
列中插入時,我必須使用公式Transaction_Date-start_date+1
,其中Transaction_Date
來自STG_Shipped_Invoiced
而start_date
來自Cal_date
表。
我用datepart (mm, Transaction_Date)
所以它給month_no
,這month_no
我們可以加入month_no
的Cal_date
表並獲取start_date
從Cal_date
表,所以,我們可以使用start_date
為式Transaction_Date-start_date+1
。
但是我很難在上面的查詢中安排這個。
你能指導我如何做到這一點嗎?
提前致謝
根據您的問題,我認為這就是您要尋找的
您需要使用cal_data
ON DATEPART(mm, STG.Transaction_Date) = C.month_no
cal_data
表進行JOIN
,在SELECT
使用DATEDIFF(D,CONVERT(DATE,STG.Transaction_Date),C.start_date) + 1
INSERT INTO [Global_Report_Staging].[dbo].[RPT_Invoice_Shipped]
(
Day_No,
Date,
Div_code,
Total_Invoiced,
Transaction_Date
)
SELECT DATEDIFF(D,CONVERT(DATE,STG.Transaction_Date),C.start_date) + 1,
CONVERT(DATE,Getdate()) as Date,
LTRIM(RTRIM(div_Code)),
SUM(tot_Net_Amt) as Total_Invoiced,
(DATEADD(DAY, -1, CONVERT(DATE, getdate())))
FROM [Global_Report_Staging].[dbo].[STG_Shipped_Invoiced] STG
INNER JOIN cal_data C
ON DATEPART(mm, STG.Transaction_Date) = C.month_no
WHERE CONVERT(DATE,Created_date ) = CONVERT(DATE,Getdate())
GROUP BY div_code,CONVERT(DATE,STG.Transaction_Date),C.start_date
該join
根據您指定什么
FROM [Global_Report_Staging].[dbo].[STG_Shipped_Invoiced] AS a
INNER JOIN Cal_date AS b ON datepart (mm, Transaction_Date)) = a.month_no
insert into [Global_Report_Staging].[dbo].[RPT_Invoice_Shipped](Day_No, Date, Div_code, Total_Invoiced, Transaction_Date)
select Transaction_Date-start_date+1, CONVERT(DATE,Getdate()) as Date, LTRIM(RTRIM(div_Code)),
sum(tot_Net_Amt) as Total_Invoiced, (dateadd(day, -1, convert(date, getdate())))
from [Global_Report_Staging].[dbo].[STG_Shipped_Invoiced] AS a
INNER JOIN Cal_date AS b ON datepart (mm, Transaction_Date)) = a.month_no
WHERE CONVERT(DATE,Created_date )=CONVERT(DATE,Getdate())
group by div_code
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.