如何在sql查询中平均一列结果

时间:2012-07-10 18:53:03

标签: sql

我有一个查询,它会提取活跃客户的数量,并查找客户活跃的总天数...我想找到此列的平均值...

是否可以拉出平均值并在这样的查询中将其显示在1行?或者这需要在报告方面完成吗?我目前的疑问是:

SELECT        
   dtCreated, bActive, dtLastUpdated, dtLastVisit, 
   DATEDIFF(d, dtCreated, dtLastUpdated) AS Difference
FROM 
   Customers
WHERE        
   (bActive = 'true') 
   AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-01 00:00:00', 102))

感谢。

1 个答案:

答案 0 :(得分:4)

使用AVG:http://msdn.microsoft.com/en-us/library/ms177677

SELECT         
   dtCreated, bActive, dtLastUpdated, dtLastVisit,  
   DATEDIFF(d, dtCreated, dtLastUpdated) AS Difference,
   AVG(DATEDIFF(d, dtCreated, dtLastUpdated)) OVER() AS AvgDifference
FROM  
   Customers 
WHERE         
   (bActive = 'true')  
   AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-01 00:00:00', 102)) 

更新它以使用OVER():http://msdn.microsoft.com/en-us/library/ms189461.aspx