0

我有下表

|id|city|job|
|12|New York|Truck driver|
|13|Chicago|Postman|
|14|New York|Postman|
|15|Las Vegas|Dealer|
|16|Las Vegas|Dealer|
|17|New York|Post Office|

我希望能够计算每个城市有多少工作,然后以 DESC 顺序返回工作最多的十个城市。像下面这样

  • 纽约 (3)
  • 拉斯维加斯 (2)
  • 芝加哥 (1)

我该如何做到这一点?

我的代码看起来像这样

 $this->db->select('city');
 $this->db->select_sum('city', 'total');
 $this->db->group_by('city'); 
 $this->db->order_by('total', 'desc'); 
 $query = $this->db->get('job', 10);

foreach ($query->result() as $row) {
    $data[] = array(
        'total' => $row->total,
        'city' => $row->city
    );
}

return $data;

我从这个线程中获得灵感:COUNT / GROUP BY with active record?

但似乎并不正确。

4

2 回答 2

0

为什么不使用$this->db->query();?

$this->db->query('SELECT CITY, COUNT(CITY) AS TOTAL FROM JOB GROUP BY CITY ORDER BY TOTAL DESC LIMIT 10');
于 2013-08-17T15:59:14.127 回答
0

干得好:-

$query = $this->db->query('SELECT city, COUNT(city) AS jobcount FROM `jobs` GROUP BY city ORDER BY jobcount DESC');

if ($query->num_rows() > 0)
    foreach ($query->result() as $row) 
        $data[] = array(
            'total' => $row->jobcount,
            'city'  => $row->city
        );

return $data;

不要忘记'jobs'用你的表名交换

于 2013-08-17T16:08:16.097 回答