PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Consulta PostgreSQL com colunas geradas

select 
t1.name,
sum(case when t2.abbrev='foo' then t1.amount*t2.amount else 0 end) as foo,
sum(case when t2.abbrev='bar' then t1.amount*t2.amount else 0 end) as bar,
sum(case when t2.abbrev='baz' then t1.amount*t2.amount else 0 end) as baz
from usage t1 inner join points t2 on t1.points_id=t2.ident
group by t1.name;

Exemplo do SQL Fiddle:http://sqlfiddle.com/#!15/cc84a/6;

Use a seguinte função do PostgreSQL para casos dinâmicos:
create or replace function sp_test()
returns void as
$$

declare cases character varying;
declare sql_statement text;
begin

select string_agg(concat('sum(case when t2.abbrev=','''',abbrev,'''',' then t1.amount*t2.amount else 0 end) as ', abbrev),',') into cases from points;

drop table if exists temp_data;

sql_statement=concat('create temporary table temp_data as select 
t1.name,',cases ,' 
from usage t1 inner join points t2 on t1.points_id=t2.ident
group by t1.name ');

execute sql_statement;

end;
$$
language 'plpgsql';

A função usa uma tabela temporária para armazenar dados de colunas dinâmicas.

Chame a função da seguinte maneira para obter dados:

select * from sp_test(); select * from temp_data;