Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

need help with a query to count distinct items

using mssql server



6:06 am on Nov 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

My query skills are sorely lacking so hopefully someone can help me with this.

My table is called IPAddresses and it contains:

DateAdded as datetime
IPAddress as varchar(15)

I want to know what each distinct IPAddress is, and I also want to know what the total count for each distinct IPAddress is. I can easily do either one, but can't figure out a way to do both so that I have both the count and the actual IPAddress being counted.

My purpose is to see which IP Addresses are hitting a site of mine the most, so sorting in descending order of the total count would be helpful.

This is a query I'll be executing manually once a day or so, so I'm not too concerned with how efficient it is.



8:49 am on Nov 16, 2010 (gmt 0)

5+ Year Member

Hi Gary,

This should do the trick:
SELECT Count(*) as hits, IPAddress From IPAddresses Group By IPAddress Order by hits desc;

Hope this help.


6:05 pm on Nov 16, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

That did the trick. Thanks very much, Peter. :)


4:16 pm on Nov 22, 2010 (gmt 0)

10+ Year Member

Even better would be:

SELECT Count(DISTINCT IPAddress), IPAddress
From IPAddresses
Order by hits desc


12:02 am on Nov 23, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member

Aren't you missing "as hits" and a group by clause? Also, won't your Count(DISTINCT IPAddress) always return a value of 1?

Featured Threads

Hot Threads This Week

Hot Threads This Month