A
A
Artem2020-04-18 09:35:47
PostgreSQL
Artem, 2020-04-18 09:35:47

How to create PostgreSQL table function with column names as arguments?

Good day to all.
Got a team

select supplier, car_category, count(car_type) from mytable group by 1,2 order by 1,2;

, which returns the supplier table I need | car_category | count
----------+----------------------+-------
Avis | compact | 4
Avis | full size | 2
Avis | Hatch | 6
Avis | intermediate | 4
Avis | sedan | 6
Avis | standard | 2
Avis | SUV | 6
Budget | compact | 8
budget | full size | 4
Budget | hatch | 2
Budget | Hatch | 2
Budget | hatchback | 4
Budget | intermediate | 8
budget | sedan | 4
Budget | standard | 4
Eurocar | compact | 5
Europcar | full size | 5
Europcar | intermediate | 15
Eurocar | standard | 10
(19 rows)

The task is to write a function that would return the same. My attempt:
create or replace function pivot_car_type(a text, b text, c text)
returns table(supplier text, category text, car_type_qty bigint) as
$$
begin
return query
select a,b,count(c) from avis.rateshop group by 1,2 order by 1,2;
end;
$$
language 'plpgsql';


But when called
select * from pivot_car_type(supplier, car_category, car_type);

I get a response like:
supplier | category | car_type_qty
----------+----------------------+--------------
supplier | car_category | 101
(1 row)
where 101 is the number of records in the table.
Those. it turns out that the function uses a command of the form:
select 'supplier', 'car_category', count('car_type') from mytable group by 1,2 order by 1,2;

but not
select supplier, car_category, count(car_type) from mytable group by 1,2 order by 1,2;

Tell me what I'm doing wrong, please :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2020-04-18
@melkij

That's the way it should be.
If you want to build a query dynamically, then build it dynamically in a variable, then send it for execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question