On 07/03/2012 06:48 AM, Stefan Schwarzer wrote:
> Hi there,
>
> I am using 9.1.3. I inserted the tablefunc extension, into a SCHEMA called tablefunc, in order to separate it from my tables. I had to create it as postgres user, but changed than the Owner of both schema and functions to my user XXX.
>
> Now, when I launch a query which includes «crosstab()» as a postgres user, everything works fine. However, if I launch it as user XXX, it complaints:
>
> ERROR: function crosstab(unknown, unknown) does not exist
> LINE 1: …ROM countries_view AS c LEFT JOIN ( SELECT * FROM crosstab( … ^
> HINT: No function matches the given name and argument types. You might need to add explicit type casts.
>
> ********** Error **********
> ERROR: function crosstab(unknown, unknown) does not exist
> SQL state: 42883
> Hint: No function matches the given name and argument types. You might need to add explicit type casts.
> Character: 84
>
>
> I looked for the other tables which are included in the query, if they belong to postgres, but they belong all to user XXX.
>
> So, what could that be?
>
> Thanks for any hints!
Are you schema qualifying the function name when you use it?
If not, does user XXX have schema tablefunc in their search_path?
>
—
Adrian Klaver
adrian(dot)klaver(at)gmail(dot)com
PostgreSQL statement uses the function
crosstab to pivot the table records, pivot means I want to convert the rows to
the column of particular column’s value and want to the others column value
respectively of converted rows.
PostgreSQL- CROSSTAB example
Suppose we have the following table
CREATE TABLE product
(
id
serial not null,
brand
text,
category
text,
qty
integer
);
— Insert some records
INSERT INTO product(brand,category,qty)
VALUES(‘Arrow’,‘Cloths’,3000);
INSERT INTO product(brand,category,qty)
VALUES(‘Samsung’,‘Mobile’,4500);
INSERT INTO product(brand,category,qty)
VALUES(‘iPad’,‘Tablet’,2000);
INSERT INTO product(brand,category,qty)
VALUES(‘Prestige’,‘Kitchen’,200);
Now,
select query
SELECT * FROM product;
Result:
id |
brand |
category |
qty |
1 |
«Arrow» |
«Cloths» |
3000 |
2 |
«Samsung» |
«Mobile» |
4500 |
3 |
«iPad» |
«Tablet» |
2000 |
4 |
«Prestige» |
«Kitchen» |
200 |
But expected
result as below
Result:
brand |
Cloths |
mobile |
Tablet |
kitchen |
«Arrow» |
3000 |
|||
«iPad» |
2000 |
|||
«Prestige» |
200 |
|||
«Samsung» |
4500 |
Using
CROSSTAB we can achieve the pivot goal, se the following query
SELECT *
FROM
crosstab(
‘SELECT brand, category, qty
FROM product
ORDER BY 1,2′,
$$VALUES (‘Cloths’::text), (‘Mobile’),(‘Tablet’),(‘Kitchen’)$$
) AS ct (brand text, Cloths int, Mobile int, Tablet int, Kitchen int);
Result:
brand |
Cloths |
Mobile |
Tablet |
kitchen |
«Arrow» |
3000 |
|||
«iPad» |
2000 |
|||
«Prestige» |
200 |
|||
«Samsung» |
4500 |
Note: If you are getting
the following error:
ERROR: function
crosstab(unknown, unknown) does not exist
LINE 2: FROM crosstab(
^
HINT: No function matches the given name and
argument types. You might need to add explicit type casts.
SQL state: 42883
Character: 17
The above error will remove executing the
following PostgreSQL statement
CREATE EXTENSION IF NOT EXISTS tablefunc;
View previous topic :: View next topic | |||||||||||||||||||||||||||||
Author | Message | ||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jeffk l33t Joined: 13 Sep 2003 |
|
||||||||||||||||||||||||||||
Back to top |
|
||||||||||||||||||||||||||||
|
You cannot post new topics in this forum |
Postgres 9.2.1 на OSX 10.9.2.
Если я запускаю следующий пример перекрестного запроса:
CREATE EXTENSION tablefunc;
CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');
SELECT *
FROM crosstab(
'select rowid, attribute, value
from ct
where attribute = ''att2'' or attribute = ''att3''
order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);
Я получаю: ERROR: extension "tablefunc" already exists
Но если я закомментирую CREATE EXTENSION
Я получаю: ERROR: function crosstab(unknown) does not exist
Как мне выбраться из этого порочного круга? Это известная проблема?
3 ответа
Вы можете изменить первую строку на:
CREATE EXTENSION IF NOT EXISTS tablefunc;
11
akbarbin
5 Дек 2017 в 10:24
Проблема в моем случае заключалась в том, что расширение tablefunc было определено для одной конкретной схемы в моей БД и недоступно для всех схем в ней.
[изменить: как объяснялось выше, «недоступен для всех схем» следует читать «не может быть загружен во всех схемах»]
Я узнал, что:
- расширение можно загрузить только в одну схему, поэтому загрузите его в «общедоступную»
- вам нужно вручную удалить расширение из одной схемы, прежде чем вы сможете загрузить его в другую
- вы можете перечислить загруженные расширения для каждой схемы в pqsl, используя команду:
df *.crosstab
[править: 4. вы можете получить доступ к расширению либо по search_path, либо загрузив его в общедоступную схему, либо явно указав схему]
7
Black
16 Апр 2014 в 03:30
В вашем ответе есть неверное представление:
и не доступен для всех схем в нем.
Все схемы в одной и той же базе данных доступны для всех сеансов в этой же базе данных (при наличии соответствующих прав). Это вопрос установки search_path
. Схемы работают так же, как каталоги/папки в файловой системе.
Кроме того, вы можете квалифицировать функцию (и даже операторы) по схеме для доступа к ней независимо от search_path
:
SELECT *
FROM my_extension_schema.crosstab(
$$select rowid, attribute, "value"
from ct
where attribute IN ('att2', 'att3')
order by 1,2$$
,$$VALUES ('att2'), ('att3')$$
) AS ct(row_name text, category_2 text, category_3 text);
Недавний связанный ответ с дополнительной информацией:
Как использовать оператор% из расширения pg_trgm?
Сомнительный crosstab()
Ваш запрос возвратил атрибуты 'att2'
и 'att3'
, но в списке определений столбцов есть три категории (category_1, category_2, category_3
), которые не соответствуют запросу.
Я удалил category_1
и добавил в crosstab() второй параметр — «безопасную» версию. Подробнее здесь:
Запрос перекрестной таблицы PostgreSQL
В стороне: не используйте value
в качестве имени столбца. Даже если Postgres это терпит. Это зарезервированное слово в стандартном SQL.
4
Community
20 Июн 2020 в 12:12