SQL Group按日期但保持记录

时间:2014-07-29 17:08:54

标签: php sql cakephp

我假设php/cakephp/sql一致。 我有一个History表,其中包含由DATETIME.类型创建的列 我会显示历史的所有记录,但是按天安排。

------------------------------------------
id   created                what
------------------------------------------
1    2014-01-01 08:00:00   Someone ran
2    2014-01-01 09:00:00   Someone cried
2    2014-01-02 10:00:00   Someone spoke
2    2014-01-02 18:00:00   Someone worked

我正在寻找的结果

array(
'2014-01-01' => array(
                      0=>array('time'=>'8:00','what'=>'Someone ran'
                      1=>array('time'=>'9:00','what'=>'Someone cried'
                     ),
'2014-01-02' => array(
                      0=>array('time'=>'10:00','what'=>'Someone spoke',
                      1=>array('time'=>'18:00','what'=>'Someone worked',
                     )
)

我完全被困了。我应该调查哪个SQL语句? GROUP不好......

1 个答案:

答案 0 :(得分:0)

如果其他评论者同意,我会在改编自this SO answer的cakephp中给出答案

 $histories = $this->History->find('all',
                    array(
                        'group'=>array('History.created')
            ));


 foreach ($histories as $item) {
                $key = date('Y-m-d',strtotime($item['History']['created']));
                if (!isset($groups[$key])) {
                    $groups[$key] = array(
                        'items' => array($item),
                        'count' => 1,
                    );
                } else {
                    $groups[$key]['items'][] = $item;
                    $groups[$key]['count'] += 1;
                }
            }