我试图按一个字段(年份)对我的实体进行分组并对其进行计数。
码:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
我似乎无法说出
COUNT(b.id) AS count
,因为它给出了一个错误,并且我不知道将什么用作
addOrderby(???, 'DESC')
值?
最佳答案
使用COUNT(b.id) AS count
时出现什么错误?可能是因为count
是保留字。尝试COUNT(b.id) AS idCount
或类似的方法。
或者,尝试$qb->addOrderby('COUNT(b.id)', 'DESC');
。
您的数据库系统是什么(mysql,postgresql等)?
关于sql-order-by - 如何在《教义2》中按数排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6000622/