user1800361
user1800361

Reputation:

how to do avg() in from count()sql

I have this T-sql to get count for each sell rep to a customer during current month I want to ask how can apply avg function to get avg visit for current month

SELECT COUNT(VisitTracking.customerID) AS #VISIT, 
       MAX(VisitTracking.visitID) AS VisitID, 
       Customers.title AS Title, 
       Customers.firstName AS [First Name], 
       Customers.LastName AS [Last Name], 
       Company.companyName AS [Company Name], 
       MAX(VisitTracking.DateVisited) AS [Date Visited], 
       CONVERT(DATE, MAX(VisitTracking.nextVisit)) AS [Next Visit], 
       Customers.customerID
FROM VisitTracking 
INNER JOIN Customers ON VisitTracking.customerID = Customers.customerID
INNER JOIN Customer_Company ON Customers.customerID = Customer_Company.customerID     
INNER JOIN Company ON Customer_Company.companyID = Company.companyID
WHERE VisitTracking.DateVisited BETWEEN '11/01/2012'  AND '11/31/2012' 
GROUP BY Customers.title, Customers.firstName, Customers.LastName, Company.companyName, Customers.customerID

Upvotes: 0

Views: 1101

Answers (2)

paparazzo
paparazzo

Reputation: 45096

Have you tried compute?

    SELECT [sParID], count([sParID]) as '#sID'
      FROM [docSVsys]
     group by [sParID]
     order by [sParID] 
   compute avg(count([sParID]))

Upvotes: 2

povilasp
povilasp

Reputation: 2396

Why not a sub select? Yeah, I know, sub select are NASTY, NOT NICE and don't perform as well. But they do get the job done when producing data for reports and analysis, so, maybe:

SELECT AVG(a.#VISIT) FROM (SELECT COUNT(VisitTracking.customerID) AS #VISIT, 
       MAX(VisitTracking.visitID) AS VisitID, 
       Customers.title AS Title, 
       Customers.firstName AS [First Name], 
       Customers.LastName AS [Last Name], 
       Company.companyName AS [Company Name], 
       MAX(VisitTracking.DateVisited) AS [Date Visited], 
       CONVERT(DATE, MAX(VisitTracking.nextVisit)) AS [Next Visit], 
       Customers.customerID
FROM VisitTracking 
INNER JOIN Customers ON VisitTracking.customerID = Customers.customerID
INNER JOIN Customer_Company ON Customers.customerID = Customer_Company.customerID     
INNER JOIN Company ON Customer_Company.companyID = Company.companyID
WHERE VisitTracking.DateVisited BETWEEN '11/01/2012'  AND '11/31/2012' 
GROUP BY Customers.title, Customers.firstName, Customers.LastName, Company.companyName, Customers.customerID) AS a

Upvotes: 0

Related Questions