簡體   English   中英

如何從另一個表中獲取列並插入到另一個表中?

[英]How to get column from another table and insert into other table?

我有兩個表Cal_dateRPT_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_Invoicedstart_date來自Cal_date表。

我用datepart (mm, Transaction_Date)所以它給month_no ,這month_no我們可以加入month_noCal_date表並獲取start_dateCal_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM