SQL Server:周期内平均值显示所有组的相同值

时间:2019-05-08 09:48:26

标签: sql-server

从客户使用情况数据中,我希望获得过去一周的使用情况以及过去52周中按客户ID分组的每周平均值。尝试执行以下操作,但获得所有clientID的总和和平均值相同的值:

declare @refdate date = '2019-05-06'

;with cte as (
select clientID, useCount, useDate from usageData where datediff(week, useDate, @refdate) <=52

)

select clientID,
    (select sum(useCount) from cte where datediff(week, useDate, @refdate) <= 1 and clientID=cte.clientID) as sumover1week,
    (select sum(useCount)/52 from cte where datediff(week, useDate, @refdate) <= 52 and clientID=cte.clientID) as avgover52weeks
    from cte 
    group by clientID 

谢谢

2 个答案:

答案 0 :(得分:1)

使用JOIN和子查询来获取数据,并在clientID上对每个子查询进行分组。将它们一起加入clientID并获得结果。如果要查看过去一年中有任何意见的人,请使用LEFT JOIN;如果只希望过去一周中有过用法的人,请使用JOIN

SELECT y.clientID, ISNULL(w.useCount, 0) as WeeklyCount, y.useCount/52 as YearlyAverage
FROM (
    SELECT clientID, SUM(useCount) as useCount
    FROM usageData 
    WHERE DATEDIFF(week, useDate, @refdate) <= 52
    GROUP BY clientID
) as y
LEFT JOIN (
    SELECT clientID, SUM(useCount) as useCount
    FROM usageData 
    WHERE DATEDIFF(week, useDate, @refdate) <= 1
    GROUP BY clientID
) as w
   ON y.clientID = w.clientID

答案 1 :(得分:1)

一种方法是删除子查询并使用案例过滤掉sumover1week的旧结果:

select 
    clientID
    ,sum(useCount*case when datediff(week, useDate, @refdate) <= 1 then 1 else 0 end)  as sumover1week,
    ,sum(useCount)/52  as avgover52weeks
from cte 
group by clientID