CakePHP中的GROUP和COUNT()多个字段

时间:2015-02-08 15:50:39

标签: mysql 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
  ),
  ...
  .....
)

更新:

我使用了查询:

$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'
    )
),

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

1 个答案:

答案 0 :(得分: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
相关问题