The use of the extension is common tablefunc
with the function crosstab
to generate the results in this way. Another alternative is to use the json functions of postgres to generate the results.
Json can be generated directly by postgres and then using the resources of the frontend programming language to make the results available in column:
with vendas as(
select
t.nome as store_nome,
c.nome as card_nome,
sum(s.valor) as total_sale
from sale s
inner join store t
on (t.id = s.store_id_fk)
inner join credit_card c
on (c.id = s.credit_card_fk)
where
data between '2017-01-01' and '2017-01-31'
group by
t.nome,
c.nome
)
select
store_nome,
json_object_agg(card_nome,total_sale) as bandeiras
from vendas
group by store_nome
store_nome | bandeiras
------------+--------------------------------------------------------------
Loja 02 | { "AMEX" : 60, "DINERS" : 60, "MASTER" : 60, "VISA" : 60 }
Loja 01 | { "AMEX" : 150, "DINERS" : 80, "MASTER" : 50, "VISA" : 100 }
(2 registros)
Data can also be returned by postgres already with the values separated by column using the operator ->
:
with vendas as(
select
t.nome as store_nome,
c.nome as card_nome,
sum(s.valor) as total_sale
from sale s
inner join store t
on (t.id = s.store_id_fk)
inner join credit_card c
on (c.id = s.credit_card_fk)
where
data between '2017-01-01' and '2017-01-31'
group by
t.nome,
c.nome
), vendas_por_loja as (
select
store_nome,
sum(total_sale) as total
from vendas
group by store_nome
), vendas_por_bandeira as (
select
store_nome,
jsonb_object_agg(card_nome,total_sale) as bandeiras
from
vendas
group by store_nome
)
select
vb.store_nome,
vb.bandeiras->'AMEX' as amex,
vb.bandeiras->'VISA' as visa,
vb.bandeiras->'DINERS' as diners,
vb.bandeiras->'MASTER' as master,
vl.total
from vendas_por_bandeira vb
inner join vendas_por_loja vl
on (vb.store_nome=vl.store_nome);
store_nome | amex | visa | diners | master | total
------------+------+------+--------+--------+-------
Loja 02 | 60 | 60 | 60 | 60 | 240
Loja 01 | 150 | 100 | 80 | 50 | 380
(2 registros)
The function json_object_agg
is available since version 9.4 of postgres.
http://bender.io/2016/09/18/dynamic-pivot-tables-with-json-and-postgresql/
https://www.postgresql.org/docs/9.4/static/functions-aggregate.html
https://www.postgresql.org/docs/current/static/tablefunc.html
Do you want to return one line for each store? You could edit the question and give a formatted one in the example, maybe an image with the example of the result in the layout similar to a table would be easier for the community people to understand your problem.
– Camilo Santos
I added the photo of how the exit needs to be. I was searching and saw that this is a dynamic table ( I had never done one), and I will need to use Crosstab, but it’s not going.
– Lucas Esbegue