我有下表:
我需要将 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/