通过CTE和数据透视表从查询表中插入

问题描述 投票:0回答:1

我有查询,该查询以枢轴格式返回结果,因此我想将其插入SQL表中。最终,我将创建一个代理工作,该工作每晚晚上10点运行并将记录插入表中。我可以找到一些示例,在这些示例中,人们使用了CTE,然后将CTE的结果放到了表格中,但是随着我对结果的关注,我们发现了更复杂的情况。

谁能帮我吗?

下面是脚本

WITH CTE as 

(SELECT

org.StudioMain,
BUD.ForecastProbability as 'Prob%',
(BUD.ForecastProbability*BUD.AmountOrgCurrency) as ForecastAmountOrg,
(BUD.ForecastProbability*CASE
WHEN org.EntityCode = 'WAU' AND org.Studio = 'Sydney' THEN 
BUD.AmountOrgCurrency/NULLIF(bud.ForecastCurrencyToNZDfx,0)
WHEN org.EntityCode = 'WAU' AND org.Studio = 'Melbourne' THEN 
BUD.AmountOrgCurrency/NULLIF(bud.ForecastCurrencyToNZDfx,0)
else BUD.AmountOrgCurrency
end) as ForecastAmountNZD


FROM EDWH.dbo.FactBudgets AS BUD
INNER JOIN [ODS].[dbo].[PeriodTriggerMain] as T ON BUD.BudgetName = T.BudgetName
LEFT JOIN EDWH.dbo.DimOrg as Org on BUD.DimOrgKey = org.DimOrgKey
LEFT JOIN ODS.dbo.DimFinPeriodDate as Period on BUD.DimFinPeriodDateKey = Period.DimFinPeriodDateKey
LEFT JOIN (SELECT DISTINCT WBS1, ProjectName, Principal, Sector FROM EDWH.dbo.DimProject where WBS2 = 
'') as PRN ON BUD.WBS1 = PRN.WBS1


WHERE 
CONVERT(varchar(10),dateadd(day,0,dateadd(month,datediff(month,0,dateadd(month, 3, 
datefromparts(left(BUD.FinPeriod, 4)-1, right(BUD.FinPeriod, 2), 1))),0)),120) BETWEEN
CONVERT(varchar(10),dateadd(day,0,dateadd(month,datediff(month,0,dateadd(month, 3, 
datefromparts(left(T.ForecastPeriod, 4)-1, right(T.ForecastPeriod, 2), 1))),0)),120) AND
CONVERT(varchar(10),dateadd(day,0,dateadd(month,datediff(month,0,dateadd(month, 14, 
datefromparts(left(T.ForecastPeriod, 4)-1, right(T.ForecastPeriod, 2), 1))),0)),120) 
)
SELECT * FROM (
SELECT
StudioMain,
Currency = 'NZD',
SUM(ForecastAmountNZD) as AmountNZD,
getdate() as Timestamp

FROM CTE as f

GROUP BY
StudioMain
) as NZD

PIVOT(
SUM(AmountNZD)
FOR [StudioMain] IN  
([AKL], [CHC], [MEL], [QNT], [SYD], [WEL], [WMT])
)
AS Pivot_Table

UNION ALL

SELECT * FROM (
SELECT
StudioMain,
Currency = 'ORG',
SUM(ForecastAmountOrg) as AmountOrg,
getdate() as Timestamp

FROM CTE as f

GROUP BY
StudioMain
) as Org

PIVOT(
SUM(AmountOrg)
FOR [StudioMain] IN
([AKL], [CHC], [MEL], [QNT], [SYD], [WEL], [WMT])
)
AS Pivot_Table

enter image description here

我想将结果插入表格;enter image description here

insert pivot ssms common-table-expression
1个回答
0
投票

根据您的理解,

  1. 您需要将基于PIVOT的SQL查询的执行结果插入表中。因此,我们将使用下面的列创建一个表,
  2. 货币,时间戳,AKL,CHC,MEL,QNT,SYD,WEL,WMT
  3. 然后,您将创建一个SQL Agent Job,您将在其中传递SQL查询以获取数据。
  4. 在源代码中,您需要提及查询中使用的表的数据库详细信息。
  5. 在目标位置,您需要提及将要创建的新表
  6. 安排此作业每天晚上10点运行
  7. 通过在步骤处执行开始作业来检查作业,以查看是否成功,并且是否将数据插入到新表中。

尽管查询具有PIVOT功能,但是将SQL代理JOB插入所需的数据到目标表将是一个简单的SQL Agent JOB。

© www.soinside.com 2019 - 2024. All rights reserved.