我有两张表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
我使用下面的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_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
。
但是我很难在上面的查询中安排这个。
你能指导我如何实现这个目标吗?
提前致谢
答案 0 :(得分:1)
根据您的问题,我认为这就是您要找的内容
您需要使用JOIN
表格cal_data
和ON 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