我希望生成一个表格,显示每个客户类型的推荐和约会之间的平均天数。我的SQL代码目前看起来像这样:
select CustomerID, CustomerType, ReferralDate, AppointmentDate,
Datediff(d, ReferralDate, AppointmentDate) as [Ref to App (Days)]
From Referrals
上面的代码生成每个客户从推荐到预约的天数列表。我需要的是每个CustomerType一行(我的数据库中目前有7种客户类型),然后是一个名为[从ref到app的平均天数]的字段。这将留下七行,每行包含从推荐到预约的平均天数。
我知道我可以使用AVG功能,但我似乎无法按照我想要的方式工作。我需要使用的总和将是这样的:(每个CustomerType的总天数)/(每个CustomerType的客户ID总数)=每个客户类型的平均天数
有没有人有任何建议?
答案 0 :(得分:1)
我认为这个查询应该做你想做的事情:
select r.CustomerType,
avg(1.0 * Datediff(day, r.ReferralDate, r.AppointmentDate)) as [Ref to App (Days)]
from Referrals r
group by r.CustomerType;
基本上,您只需要一个group by
并删除无关的列。