2015-02-08 36 views
0

多个字段这是我的数据库:GROUP和COUNT()在CakePHP中

week, subbizname, devicetype 
20141203, common, PC 
20141203, unknown, PC 
20141210, KRsinKD, SP 
20141210, unknown, PC 
20141217, Unknown, SP 
20141217, Chintai, TAB 
.... 

我想获得的记录数为每一个独特的devicetype情侣/周。 例如:

array(
    20141203 => array(
    'PC'=>2, 
    'TAB'=>0, 
    'SP'=>0 
), 
    20141210 => array(
    'PC'=>1, 
    'TAB'=>0, 
    'SP'=>1 
), 
    ... 
    ..... 
) 

UPDATE:

我已经使用查询:

$data = $this->Test->find('all', array(
     'conditions'=>array(
      'OR'=>array(
       array('devicetype'=>'PC'), 
       array('devicetype'=>'SP'), 
       array('devicetype'=>'TAB'), 
      ) 
     ), 
     'fields'=>"devicetype,week,COUNT(devicetype) AS countDevice", 
     'group'=>"week,devicetype" 
    )); 

事情是,它返回是这样的:

(int) 0 => array(
    'Test' => array(
     'devicetype' => 'PC', 
     'week' => '20141126' 
    ), 
    (int) 0 => array(
     'countDevice' => '34844' 
    ) 
), 
(int) 1 => array(
    'Test' => array(
     'devicetype' => 'SP', 
     'week' => '20141126' 
    ), 
    (int) 0 => array(
     'countDevice' => '32401' 
    ) 
), 
(int) 2 => array(
    'Test' => array(
     'devicetype' => 'TAB', 
     'week' => '20141126' 
    ), 
    (int) 0 => array(
     'countDevice' => '4256' 
    ) 
), 
(int) 3 => array(
    'Test' => array(
     'devicetype' => 'PC', 
     'week' => '20141203' 
    ), 
    (int) 0 => array(
     'countDevice' => '96564' 
    ) 
), 
(int) 4 => array(
    'Test' => array(
     'devicetype' => 'SP', 
     'week' => '20141203' 
    ), 
    (int) 0 => array(
     'countDevice' => '97450' 
    ) 
), 

但我不管理获得预期的结果。 当然必须有更好的办法。 我该如何解决这个问题?

+0

“SELECT周,设备类型,COUNT(*)AS CNT从TBL GROUP BY周,设备类型” 应该工作。 – Ananth 2015-02-08 15:54:38

+0

是的。谢谢@安南! – RyanPudo 2015-02-08 16:18:07

回答

0

使用您的$ data变量,你可以这样做:

$d = array(); 
foreach ($data as $value) { 
    $week = $value['Test']['week']; 
    if (isset($d[$week])) { 
     $d[$week][$value['Test']['devicetype']] = $value[0]['countDevice']; 
    } else { 
     $d[$week] = array($value['Test']['devicetype'] => $value[0]['countDevice']); 
    } 
} 

print_r($d); // $d will contain the data in your required format