在交叉表的选择语句中绑定一个参数


Bind a parameter within the select statement of crosstab

我有一个用交叉表函数创建数据透视表的语句。我的目标是让用户输入一个值列表,即客户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),并与三个令牌绑定。在执行时,我得到错误消息:' error: could not decide data type of parameter $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()函数而言,

只是一个普通字符串。与在SQL语句级别绑定不同,您可以定义一个字符串,然后将其中的参数值sprintf()传递给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));