带有Doctrine的累积DQL

时间:2009-10-03 09:59:45

标签: php doctrine sum dql

我很难找到合适的DQL来生成累积总和。我可以用普通的SQL做到这一点,但是当谈到DQL时,我无法掌握它。

以下是它在SQL中的外观:

    SELECT s.name, p.date_short, p.nettobuy,
    (select sum(pp.nettobuy) as sum from price pp where pp.stock_id = p.stock_id and p.broker_id = pp.broker_id and pp.date_short <= p.date_short) as cumulative_sum
FROM price p
    left join stock s on p.stock_id = s.id
    group by p.stock_id, p.date_short
    order by p.stock_id, p.date_short

SELECT s.name, p.date_short, p.nettobuy, (select sum(pp.nettobuy) as sum from price pp where pp.stock_id = p.stock_id and p.broker_id = pp.broker_id and pp.date_short <= p.date_short) as cumulative_sum FROM price p left join stock s on p.stock_id = s.id group by p.stock_id, p.date_short order by p.stock_id, p.date_short

由于

2 个答案:

答案 0 :(得分:3)

嘿,我查看了Doctrine 1.2的文档,创建查询的方法是(注意别名):

$query = Doctrine_Query::create();
$query->addSelect('AVG(price) as price');
$query->addSelect('AVG(cost) as cost');
// as many addSelect() as you need
$query->from('my_table');

输出创建的SQL查询:

echo $query->getSqlQuery();

执行声明:

$product = $query->fetchOne();

要访问检索到的数据是:

echo $product->getPrice();
echo $product->getCost();

阅读Group By Clauses上的其余文档。

答案 1 :(得分:2)

您只需在DQL的选择部分中指定总和:

$query = Doctrine_Query::create()
   ->select('sum(amount)')
   ->from('some_table');

查看Doctrine文档中的this page以获取更多信息。