Jump to content

Playing w/ COUNT, GROUP BY, & ORDER BY


yarub

Recommended Posts

So I'm kind of lost as to how I'd do this. Hopefully someone can help. I track every ip that views a certain page on my site. If it's their first view, it goes into the row as firstvisit='1'. If they come back at a later time (at least 180 seconds later), it tracks it as 0.

What I'm trying to do is create an output that would show the IPs and how many times they've viewed the page. Basically, I want to count all rows in the table; grouped by IP. I can do that part. That's not the problem. My problem is that I want to be able to print them out so that it descends from the IPs who have visited most to the people who only came the one time.

1.2.3.4 || 10 Views
4.5.6.7 || 8 Views
6.7.8.9 || 4 Views
2.7.3.3 || 1 View
4.8.2.6 || 1 View
3.5.7.9 || 1 View

[code]$query = mysql_query("select COUNT(id), id, ip, dateline FROM tablename GROUP BY ip");
while($row = mysql_fetch_array($query)){[/code]

Obviously this only does the first part of what I need. I don't know how to print them out so that it descends from the most views to the least. Can anyone help?
Link to comment
Share on other sites

Change your query to this:

[code=php:0]$sql = "select COUNT(id), id, ip, dateline FROM tablename GROUP BY ip";
$result = mysql_query($sql) or die("Error in $sql: " . mysql_error());[/code]


That will display what the error was.. then we can fix it based on that :)
Link to comment
Share on other sites

Hmph.  Well, you can order by aggregates in postgresql.  If mysql doesn't let you do that, then make it a subquery:

[code=php:0]SELECT * FROM (select COUNT(id) AS count_id, id, ip, dateline FROM tablename GROUP BY ip) AS foo ORDER BY count_id DESC[/code]


Semantically that's identical, but it may be less efficient due to use of a subquery.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.