Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT / GROUP BY with active record?

Tags:

I have a table with the following info:

id  |  user_id  |  points -------------------------- 1   |  12       |  48 2   |  15       |  36 3   |  18       |  22 4   |  12       |  28 5   |  15       |  59 6   |  12       |  31  etc. 

What I want is a top 10 (array) with most entries per user_id (order high to low). So using the table above I need the following array in return:

  • 12 => 3 rows
  • 15 => 2 rows
  • 18 => 1 row
  • etc.

How can I do this with CodeIgniter using the active record query method? Can this be done with COUNT and GROUP BY user_id?

like image 393
24creative Avatar asked Jan 24 '12 14:01

24creative


People also ask

Can we use count with group by?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I count by group by in SQL?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.


2 Answers

I believe you'll want something like this:

 $this->db->select('user_id, COUNT(user_id) as total');  $this->db->group_by('user_id');   $this->db->order_by('total', 'desc');   $this->db->get('tablename', 10); 

This will produce a result like

|  USER_ID |  TOTAL  | |    12    |    3    | |    15    |    2    | |    18    |    1    | 

UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.

like image 73
Brett DeWoody Avatar answered Sep 21 '22 05:09

Brett DeWoody


Although it is a late answer, I would say this will help you...

$query = $this->db               ->select('user_id, count(user_id) AS num_of_time')               ->group_by('user_id')               ->order_by('num_of_time', 'desc')               ->get('tablename', 10); print_r($query->result()); 
like image 37
NULL Avatar answered Sep 23 '22 05:09

NULL