我试图将新列添加到名为#opp_level的现有临时表中。此新列应按帐号反映当前截止日期前6个月的平均支出。
我下面尝试了以下2种方法,但没有成功。
方法1:
SELECT [Close Date], [Prior 6 Mo Date], [Opportunity Id], [Account Name], [Account Number], [Total Opportunity Amount], AVG([Total Opportunity Amount]) OVER ( PARTITION BY [Account Number] ORDER BY [Close Date] RANGE BETWEEN [Prior 6 Mo Date] and [Close Date] --also tried BETWEEN unbounded preceding and current row ) FROM #opp_level ORDER BY [Close Date], [Prior 6 Mo Date], [Opportunity Id], [Account Name], [Account Number], [Total Opportunity Amount]
方法2:
select a.[Close Date],a.[Total Opportunity Amount], avg(b.[Total Opportunity Amount]) AS [Prior 6 Mo Avg] from #opp_level a join #opp_level b on b.[Close Date] between dateadd(MONTH, -6, a.[Close Date]) and a.[Close Date] group by a.[Close Date], a.[Total Opportunity Amount] ORDER BY a.[Close Date]
我的当前数据集看起来没有前6个月平均列。这是我要添加的列。
Close Date Prior 6 Mo Date Opportunity Id Account Name Account Number Total Opportunity Amount Prior 6 Month Avg Opp Spend
1/1/2018 7/1/2017 12345 A Team 8763496 50 50
6/1/2018 12/1/2017 12345 A Team 8763496 1000 525
11/1/2018 5/1/2018 12345 A Team 8763496 500 750
1/1/2018 7/1/2017 67890 B Team 9812081 300 300
6/1/2018 12/1/2017 67890 B Team 9812081 2000 1150
11/1/2018 5/1/2018 67890 B Team 9812081 80 1040
答案 0 :(得分:0)
我认为您快到了。在您的第一个查询中,只需替换为:
AVG([Total Opportunity Amount]) OVER (
PARTITION BY [Account Number]
ORDER BY [Close Date]
RANGE BETWEEN [Prior 6 Mo Date] and [Close Date] --also tried BETWEEN
unbounded preceding and current row
对此:
AVG([Total Opportunity Amount]) OVER (
PARTITION BY [Account Number]
ORDER BY [Close Date]
ROWS BETWEEN 1 preceding and current row)