我有查询,该查询以枢轴格式返回结果,因此我想将其插入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
根据您的理解,
尽管查询具有PIVOT功能,但是将SQL代理JOB插入所需的数据到目标表将是一个简单的SQL Agent JOB。