在交叉表

时间:2015-08-10 10:56:37

标签: php postgresql pdo

我有一个声明,它使用交叉表函数创建一个数据透视表。我的目标是让用户输入值列表,即客户ID,并使查询返回包含每个客户和月份值的数据透视表。我为每个输入的customer_id创建一个令牌,并希望将每个令牌绑定到相应的值。

生成的查询如下所示:

SELECT * FROM crosstab (
  $$SELECT customer_id, month, value FROM tcustomers WHERE customer_id IN (:id_0, :id_1, :id_2)
  GROUP BY month, customer_id
  ORDER 1,2$$, $$SELECT UNNEST('{1,2,3,4,5,6,7,8,9,10,11,12}'::text[])$$
) AS ct("Customer" text, "1" text, "2" text, "3" text, "4" text, "5" text, "6" text, "7" text, "8" text, "9" text, "10" text, "11" text, "12" text)

结果如下:

          |1|2|3|4|5|6|7|8|9|10|11|12
customer_1|0|0|0|0|100|0|1|...
customer_2|1|0|2|200|0|0|1|...
customer_3|1|0|2|200|0|0|1|...
....

在此示例中,用户输入了绑定到三个令牌的三个客户ID(customer_1,customer_2,customer_3)。执行后,我收到错误消息:'错误:无法确定参数$ 1'的数据类型

我尝试用单引号替换$$引号并使用双引号('')转义语句中的单引号,但后来在我的标记所在的位置出现语法错误。

我可以通过简单地将输入值直接放入语句中而无需绑定即可使用它,但我真的更喜欢使用绑定。

这一切都可能吗?

1 个答案:

答案 0 :(得分:1)

这段代码:

$$SELECT customer_id, month, value
FROM tcustomers
WHERE customer_id IN (:id_0, :id_1, :id_2)
GROUP BY month, customer_id
ORDER 1,2$$
crosstab()函数而言,

只是一个常规字符串。您可以定义一个字符串,然后sprintf()参数值并将其传递给SQL语句,而不是在SQL语句级别进行绑定:

$sql = sprintf('SELECT customer_id, month, value ' .
               'FROM tcustomers ' .
               'WHERE customer_id IN (%s, %s, %s) ' .
               'GROUP BY month, customer_id ' .
               'ORDER 1,2', $id_0, $id_1, $id_2);

$result = pg_query_params($dbconn,
  'SELECT * FROM crosstab ($1, ' .
      '$$SELECT unnest(\'{1,2,3,4,5,6,7,8,9,10,11,12}\'::text[])$$ ' .
  ') AS ct("Customer" text, "1" text, "2" text, "3" text, "4" text, "5" text, "6" text, "7" text, "8" text, "9" text, "10" text, "11" text, "12" text);',
  array($sql));
相关问题