在我的Symfony2项目中,我想仅为某些行获取列(Field1)的总和(Field2 = 1):
id Field1 Field2
1 10 1
2 20 1
3 30 0
4 40 1
5 50 0
在这个例子中,我想得到70的结果(第1,2和4行的总和)。
自从我使用Oracle以来,我的查询在我的SQL GUI中运行良好:
SELECT
SUM(decode(Field2, 1, Field1, 0)) AS total
FROM myTable
由于Doctrine不承认Oracle decode function,我试图创建我的:
namespace MyBundle\DQL;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\SqlWalker;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
/**
* "DECODE" "(" Expression "," Search "," Result "," Default ")"
*/
class DecodeFunction extends FunctionNode
{
public $expression;
public $search;
public $result;
public $default;
public function getSql(SqlWalker $sqlWalker)
{
return 'decode(' . $this->expression->dispatch($sqlWalker) . ','
. $this->search->dispatch($sqlWalker) . ','
. $this->result->dispatch($sqlWalker) . ','
. $this->default->dispatch($sqlWalker) . ')';
}
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->expression = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->search = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->result = $parser->StringPrimary();
$parser->match(Lexer::T_COMMA);
$this->default = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
config.yml
doctrine:
orm:
entity_managers:
default:
auto_mapping: true
...
dql:
string_functions:
decode: MyBundle\DQL\DecodeFunction
我的查询器:
$qb = $this->createQueryBuilder('e');
$qb
->select('SUM(decode(e.Field2, :expect, e.Field1, :default)')
->setParameter('expect', 1)
->setParameter('default', 0);
但我收到了这个错误:
[Semantical Error] line 0, col 62 near 'Field2,': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
那么我做错了什么? 也许有一个更简单的解决方案?
由于