SQL Server 2014中的平均7天

时间:2016-04-22 16:12:46

标签: sql sql-server sql-server-2014

我需要修改以下T-SQL语句,以包含7天的平均收入。

我需要在以下代码中包含哪些内容才能实现这一目标?

SELECT 
    CAST(create_dtg AS DATE) DATE, 
    SUM([agent_rev] + [anchor_rev] + [corp_rev] + [offsite_rev]) AS RevenueTotals, 
    SUM([media_est_cost] + [other_cost]) AS COSTTOTALS 
FROM   
    [dbo].[dw_rpt_traffic] 
WHERE  
    [create_dtg] >= ( Getdate() - 90 ) 
--GROUP BY CREATE_DTG 
--ORDER BY CREATE_DTG ASC 

我也尝试过使用Parttion,然而,这会返回与Revenuetotals相同的值。

Select a.dte, a.revenuetotals, a.COSTTOTALS, AVG(A.RevenueTotals) OVER     (PARTITION BY a.dte ORDER BY a.dte ROWS 7 PRECEDING) as Day7Avg
from
(
   select CAST(CREATE_DTG AS DATE) as dte, 
          SUM([AGENT_REV]+[ANCHOR_REV]+[CORP_REV]+[OFFSITE_REV]) as RevenueTotals,
          SUM([MEDIA_EST_COST]+[OTHER_COST]) as COSTTOTALS
    FROM [dbo].[dw_rpt_traffic]
    where [CREATE_DTG] >= (GetDate() - 90)
    GROUP BY CREATE_DTG
    ) as A
 Group by a.dte, a.revenuetotals, a.COSTTOTALS
 order by a.dte

谢谢,凯伦

2 个答案:

答案 0 :(得分:1)

可能最简单的方法是使用outer apply

with rt as (
       select CAST(CREATE_DTG AS DATE) as dte, 
              SUM([AGENT_REV]+[ANCHOR_REV]+[CORP_REV]+[OFFSITE_REV]) as RevenueTotals,
              SUM([MEDIA_EST_COST]+[OTHER_COST]) as COSTTOTALS
       from [dbo].[dw_rpt_traffic]
       where [CREATE_DTG] >= (GetDate() - 90)
      )
select rt.*, rolling.avgrt
from rt outer apply
     (select avg(rt2.RevenueTotals) as avgrt
      from rt rt2
      where rt2.dte >= dateadd(day, -6, rt.dte) and
            rt2.dte <= rt.dte
     ) rolling
order by dte;

答案 1 :(得分:1)

对于滚动聚合,我通常使用带有OVER的{​​{1}}子句。

ROWS [...] PRECEDING [...]

上表是使用以下内容生成的:

WITH    cte
          AS ( SELECT   x.Date
                       ,x.Revenue
                       ,AVG(x.Revenue) OVER ( ORDER BY x.Date 
                                              ROWS BETWEEN 6 PRECEDING AND CURRENT ROW 
                        ) AS [MA7]
               FROM     ( SELECT    CAST(t.Date AS DATE) AS [Date]
                                   ,SUM(t.Revenue) AS [Revenue]
                          FROM      #tmp t
                          WHERE     CAST(t.Date AS DATE) > CAST(GETDATE() - 96 AS DATE)
                          GROUP BY  CAST(t.Date AS DATE)
                        ) x
             )
    SELECT  c.Date
           ,c.Revenue
           ,c.MA7
    FROM    cte c
    WHERE   c.Date > CAST(GETDATE() - 90 AS DATE)
    ORDER BY c.Date;