查找带别名的语句

时间:2013-05-31 21:41:52

标签: postgresql cakephp

我正在尝试根据用户输入按日,月或年对查询的响应进行分组。

要执行此操作,我要从log_timeAS when中提取日期,月份或年份,然后尝试GROUP BY when,但CakePHP说:

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "when" LINE 1: ...2-31' GROUP BY "Passenger"."route_id", "Route"."name", when ^

以下是我的函数调用示例,其中分组为“月份”。

$fields = array(
    "CONCAT(DATE_PART('year', \"Passenger\".\"log_time\"), '-', DATE_PART('month', \"Passenger\".\"log_time\")) AS when", 
    "Passenger.route_id", 
    "Route.name", 
    "SUM(Passenger.embarked) AS embarked"
    );
$conditions = array(
    "Passenger.log_time >=" => $start, 
    "Passenger.log_time <=" => $end
    );
$group = array("Passenger.route_id", "Route.name", "\"when\"");

return $this->find('all', array('fields' => $fields, 'conditions' => $conditions, 'group' => $group));

这是在Cake 2.3.5上使用Postgres。有没有其他人想出如何做到这一点?

1 个答案:

答案 0 :(得分:1)

when是与CASE一起使用的关键字。看起来PostgreSQL可以发现when中的select只是一个标识符,但没有足够的上下文可以在GROUP BY中找出它。我会在两个地方引用它:

"CONCAT(DATE_PART('year', \"Passenger\".\"log_time\"), '-', DATE_PART('month', \"Passenger\".\"log_time\")) AS \"when\"", 

$group = array("\"when\"", "Passenger.route_id", "Route.name");