每日平均完成的事件(以月为单位)

时间:2017-03-12 15:58:16

标签: sql sql-server

使用SQL,如何计算每月平均已完成事件数?

示例数据:

ID  Fullname    Events  Status  DateContacted   UserID
1   Jack    Phone Call  Completed   2017-03-10 00:00:00.000 14587bg   
2   Dawn    Meeting Completed   2017-03-08 00:00:00.000 15879uj   
3   Helen   Phone Call  NULL    2017-02-02 00:00:00.000 89751po   
4   Sam Appointment Completed   2017-02-10 00:00:00.000 35784ly   
5   David   Skype   Completed   2017-01-01 00:00:00.000 3337jy    
6   Jack    Skype   Completed   2017-01-14 00:00:00.000 14587bg 

谢谢

1 个答案:

答案 0 :(得分:1)

计算完成的事件数量并计算当月的天数。我假设你不关心没有事件的日子。

select year(datecontacted) as yyyy, month(datecontacted) as mm,
       (sum(case when status = 'Completed' then 1.0 else 0 end) / 
        count(distinct cast(datecontact as date))
       ) as avg_completed_per_day
from sample s
group by year(datecontacted), month(datecontacted)
order by yyyy, mm;