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
https://forums.phpfreaks.com/topic/28831-playing-w-count-group-by-order-by/
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 :)
Then you can go for temporary table.
Because the count(id) will work only for that line..can't caompare it with other row values.
So my suggestion would be , first store the result in temporary table and then execute the query order by that count column.

Regards,
Joshi.
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.