简体   繁体   中英

How to Average a column of results in sql query

I have a query which pulls the number of active customers and finds the total number of days the customer has been active... I would like to find the average of this column...

Is it possible to pull the average and display it on 1 line in a query like this? Or would this need to be done on the reporting side? My current query is:

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))

Thanks.

Use 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)) 

Updated it to use OVER(): http://msdn.microsoft.com/en-us/library/ms189461.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM