Doctrine2 - 使用group by方法为每个月添加总计

时间:2015-08-13 17:39:49

标签: mysql doctrine-orm zend-framework2

我有下表:

enter image description here

我要求将SUM(总计),SUM(成本),SUM(净)分组为每个月的总计。

到目前为止,我有以下疑问:

返回单个全局总计:

$qb ->add('select','SUM(u.total) as Total, Sum(u.cost) as Cost, Sum(u.net) as Net')
      ->where('u.status = :status')
      ->setParameter('status' , 1);

返回按创建日期分组的总计:

$qb ->add('select','SUM(u.total) as Total, Sum(u.cost) as Cost, Sum(u.net) as Net')
      ->groupBy('u.created')
      ->where('u.status = :status')
      ->setParameter('status' , 1);

我如何按天或月或年退货?

1 个答案:

答案 0 :(得分:0)

好的,好像我解决了这个问题。

Doctrine查询构建器支持子字符串,因此如果日期如下所示:

2015-08-13 14:02:15

我们可以使用子字符串来提取我们想要的部分,然后使用orderBy方法来列出它们。

按日,小时,分钟和秒制作列表,简单。

这是模板:

$qb ->add('select','SUM(u.total) as Total, Sum(u.cost) as Cost, Sum(u.net) as Net, SUBSTRING(u.created, 6, 2) as Month')
            ->groupBy('Month')
            ->where('u.status = :status')
            ->setParameter('status' , 1);

只需将SUBSTRING值替换为:

SUBSTRING(u.created, 1, 4) for Year
SUBSTRING(u.created, 6, 2) for Month
SUBSTRING(u.created, 9, 2) for Day

日和月分别会分别持续多年和几个月,因此需要进一步检查。

如果有人感兴趣,我的代码是这样的,我使用多个日,月和年属性来确保数据不会聚合。

public function getSalesBy($date)
    {

        if (!in_array($date,['day','month','year']))
        {
            return [];
        }

        $qb = $this->ordersRepository->createQueryBuilder('u');

        if ($date == 'day')
        {
            $qb->add('select','SUM(u.total) as total, Sum(u.cost) as cost, Sum(u.net) as net, SUBSTRING(u.created, 9, 2) as day, SUBSTRING(u.created, 6, 2) as month, SUBSTRING(u.created, 1, 4) as year');
            $qb->groupBy('year,month,day');
        }

        if ($date == 'month')
        {
            $qb->add('select','SUM(u.total) as total, Sum(u.cost) as cost, Sum(u.net) as net, SUBSTRING(u.created, 9, 2) as day, SUBSTRING(u.created, 6, 2) as month, SUBSTRING(u.created, 1, 4) as year');
            $qb->groupBy('year,month');
        }

        if ($date == 'year')
        {
            $qb->add('select','SUM(u.total) as total, Sum(u.cost) as cost, Sum(u.net) as net, SUBSTRING(u.created, 9, 2) as day, SUBSTRING(u.created, 6, 2) as month, SUBSTRING(u.created, 1, 4) as year');
            $qb->groupBy('year');
        }

        $qb->where('u.status = :status')->setParameter('status' , 1);


        return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

    }