如何从另一个表中获取列并插入到其他表中?

时间:2015-05-19 06:03:26

标签: sql sql-server sql-server-2008 tsql

我有两张表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

我使用下面的insert语句在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

插入Day_No表格中的RPT_Invoice_Shipped列时, 我必须使用公式Transaction_Date-start_date+1,其中Transaction_Date来自STG_Shipped_Invoicedstart_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

但是我很难在上面的查询中安排这个。

你能指导我如何实现这个目标吗?

提前致谢

2 个答案:

答案 0 :(得分:1)

根据您的问题,我认为这就是您要找的内容

您需要使用JOIN表格cal_dataON DATEPART(mm, STG.Transaction_Date) = C.month_no使用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

答案 1 :(得分:1)

根据您指定的内容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