本文介绍了在PostgreSQL中使用crosstab()时引号不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表t1,如下所示:

I have a table t1 as below:

create table t1 (
  person_id int,
  item_name varchar(30),
  item_value varchar(100)
);

此表中有五个记录:

person_id | item_name | item_value
   1        'NAME'      'john'
   1        'GENDER'    'M'
   1        'DOB'       '1970/02/01'
   1        'M_PHONE'   '1234567890'
   1        'ADDRESS'   'Some Addresses unknown'

现在,我想使用交叉表函数提取NAMEGENDER数据,因此我将SQL编写为:

Now I want to use crosstab function to extract NAME, GENDER data, so I write a SQL as:

select * from crosstab(
  'select person_id, item_name, item_value from t1
   where person_id=1 and item_name in ('NAME', 'GENDER') ')
as virtual_table (person_id int, NAME varchar, GENDER varchar)

我的问题是,您看到crosstab()中的SQL包含条件item_name,这将导致引号不正确.我该如何解决这个问题?

My problem is, as you see the SQL in crosstab() contains condition of item_name, which will cause the quotation marks to be incorrect.How do I solve the problem?

推荐答案

为避免对如何转义单引号和通常简化语法的任何混淆,请使用 美元引号 作为查询字符串:

To avoid any confusion about how to escape single quotes and generally simplify the syntax, use dollar-quoting for the query string:

SELECT *
FROM   crosstab($$
    SELECT person_id, item_name, item_value
    FROM   t1
    WHERE  person_id = 1
    AND    item_name IN ('NAME', 'GENDER')
    $$) AS virtual_table (person_id int, name varchar, gender varchar)

并且您应该在查询字符串中添加ORDER BY.我引用 tablefunc模块手册:

And you should add ORDER BY to your query string. I quote the manual for the tablefunc module:

更多详细信息:

  • PostgreSQL Crosstab Query
  • Insert text with single quotes in PostgreSQL

这篇关于在PostgreSQL中使用crosstab()时引号不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:36