查询平均值和滚动12个月的平均值

时间:2016-06-16 13:13:28

标签: sql sql-server average window-functions getdate

我希望能够找出每个客户的更改数量在过去12个月内的平均每月平均值和滚动平均值。

SELECT 
    crq_requested_by_company as 'Customer',
    COUNT(crq_number) as 'Number of Changes'
FROM 
    change_information ci1
GROUP BY 
    crq_requested_by_company

目前我正在计算总数,我的结果看起来像这样

crq_requested_by_company    count   
A                             4
B                             2
C                             2269
D                             7696
E                             110
F                             91
G                             33

我将使用的日期列称为“start_date”。

我认为需要GETDATE()来计算过去12个月的滚动平均值。

评论后的其他信息:

使用代码

;WITH CTE as
(
SELECT 
crq_requested_by_company as Customer,
COUNT(crq_number) Nuc,
dateadd(month, datediff(month, 0, crq_start_date),0) m
FROM 
change_information ci1
WHERE
crq_start_date >= dateadd(month,datediff(month, 0,getdate()) - 12,0)
GROUP BY 
crq_requested_by_company,
datediff(month, 0, crq_start_date)
)
SELECT 
Customer,
avg(Nuc) over (partition by Customer order by m) running_avg,
m start_month,
avg(Nuc) over (partition by Customer) simply_average
FROM
CTE
ORDER BY Customer, start_month

这给出了结果

Customer    running_avg start_month      simply_average
A                8      01/01/2016 00:00 13
A                10     01/02/2016 00:00 13
A                10     01/03/2016 00:00 13
A                11     01/04/2016 00:00 13
A                14     01/05/2016 00:00 13
A                13     01/06/2016 00:00 13
B                1      01/01/2016 00:00 1
C                3      01/01/2016 00:00 2
C                3      01/02/2016 00:00 2
C                2      01/03/2016 00:00 2
C                2      01/04/2016 00:00 2
C                2      01/05/2016 00:00 2
C                2      01/06/2016 00:00 2

它需要看起来像这样,以上结果的平均值 - 上述6个月的平均值(我目前只有6个月的数据,最终需要12个)

Customer   avg_of_running_avg
A          11
B          1
C          2

1 个答案:

答案 0 :(得分:2)

试试这个,它应该适用于使用运行平均值的sqlserver 2012:

;WITH CTE as
(
SELECT 
    crq_requested_by_company as Customer,
    COUNT(crq_number) Nuc,
    dateadd(month, datediff(month, 0, start_date),0) m
FROM 
    change_information ci1
WHERE
  start_date >= dateadd(month,datediff(month, 0,getdate()) - 12,0)
GROUP BY 
    crq_requested_by_company,
    datediff(month, 0, start_date)
)
SELECT 
  Customer,
  avg(Nuc) over (partition by Customer order by m) running_avg,
  m start_month,
  avg(Nuc) over (partition by Customer) simply_average
FROM
  CTE
ORDER BY Customer, start_month