1

I made MSSQL query that calculates total unique IP address and total IP records for past 30 days.

SELECT count(IPAddress) AS totalPageHits, count(DISTINCT IPAddress) AS totalVisitors, count(DateTime)
FROM recordTable
WHERE DateTime > GETDATE()-30

Now I am having a hard time to calculate average daily page hits and average daily unique visitors. I have tried to use AVG but it gives me an error message saying "Operand data type varchar is invalid for avg operator."
Any help is greatly appreciated.

2
  • 1
    You'd need to group on an appropriate date interval...
    – Marc B
    Oct 4, 2012 at 18:38
  • VARCHAR datatype cannot be averaged, you need to use int or bigint
    – Mr. Alien
    Oct 4, 2012 at 18:40

2 Answers 2

3
SELECT  AVG(HitCount) as AverageHits,
    AVG(UniqueHitCount) As AverageUniqueHits
FROM
(
SELECT  COUNT(IPAddress) as HitCount,
        COUNT(DISTINCT IPAddress) as UniqueHitCount,
        DATEDIFF(d, GETDATE(), DateTime) as Day
FROM tblHitCounter
WHERE DateTime > GETDATE() - 30
GROUP BY DATEDIFF(d, GETDATE(), DateTime)
) sub
2
  • It worked! thank you so much for your help. Iv spend many hours trying to Google it and figure this thing out. Oct 4, 2012 at 19:06
  • 1
    I'm glad that worked for you... I've had to do a lot of SQL reporting over the years :D
    – BlakeH
    Oct 4, 2012 at 19:09
2

You need to group this by day and then do the averages:

select avg(totalPageHits) as avgDailyTotalPageHits,
       avg(totalVisitors) as avgDailyTotalVisitors
from (SELECT cast(DateTime as date) as thedate,
             count(IPAddress) AS totalPageHits,
             count(DISTINCT IPAddress) AS totalVisitors, count(DateTime) as cnt
      FROM recordTable
      WHERE DateTime > GETDATE()-30
      group by cast(DateTime as date)
     ) t
4
  • Yours is the correct answer - I had a brain-fart: avg(count(...)) would always equal that number, if it worked. Aggregate functions cannot be nested.
    – BryanH
    Oct 4, 2012 at 18:49
  • Can you please also tell me what is the {t} stands for. Because I get an error saying "No column name was specified for column 4 of 't'." Thank you for your help. Oct 4, 2012 at 19:02
  • @GordonLinoff - (Re you comment on the now deleted answer..) Fyi, ColdFusion just hands off SQL to your database. So supported operations depend on your database type and driver as usual.
    – Leigh
    Oct 4, 2012 at 19:02
  • 1
    @crashtestxxx - The t is a table alias. The error probably means you need to add a column alias to the count: count(DateTime) AS NeedsAnAliasHere
    – Leigh
    Oct 4, 2012 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.