mysql - Doctrine2 - 使用分组方法添加每个月的总计

标签 mysql doctrine-orm zend-framework2

我有下表:

enter image description here

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

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

返回单个全局总计:

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

如何按天、按月或按年返回?

最佳答案

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

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

    }

关于mysql - Doctrine2 - 使用分组方法添加每个月的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31994994/

相关文章:

mysql - 如何将层次信息存储到数据库中?

mysql - 可以在 mysql 中创建的数据库的最大限制?

php - laravel Eloquent 地从同一列的两个字段中获取最小值

php - 为什么实体 getter 返回 null 而不是 0?

php - 学说 2 : inheritance mapping join with parent table

php - 使用 doctrine 2 DBAL 加入子查询

php - 如何使用 php 在 Intel-xdk 中显示来自 MySQL 的图像

php - Symfony2 功能测试 : Is a database required or not?

php - 在 "put"方法中获取 zend 框架中的 post 参数

php - 从同一 Controller 文件访问 2 个不同的表