Doctrine2 - 使用 group by 方法添加每个月的总数

Doctrine2 - using group by method to add totals for each month

我有以下 table:

我需要将 SUM(total)、SUM(cost)、SUM(net) 分组为每个月的总计。

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

Returns单全球总计:

$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);

Returns 按创建日期分组的总数:

$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);

如何return按天、月或年?

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

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

2015-08-13 14:02:15

我们可以用substring把我们想要的部分拉出来,然后用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);

    }