I want to make a dynamic pivot on pgsql table
Original table :
time | strategy | pnl |
---|---|---|
1 | a | 100 |
2 | a | 200 |
3 | a | 300 |
1 | b | 1000 |
2 | b | 2000 |
1 | c | 22 |
target table :
time | sum | a | b | c |
---|---|---|---|---|
1 | 1132 | 100 | 1000 | 32 |
2 | 2200 | 200 | 2000 | 0 |
3 | 22 | 0 | 0 | 22 |
the problem that the strategy content is dynamic i can have sometimes over 40 unique values (in this example there are only 3 a,b,c )
i have the following code it looks like a good start but the are some problems i cannot solve
SELECT time,
--sum(case when strategy='a' then pnl else 0 end) AS "a" ,
--sum(case when strategy='b' then pnl else 0 end) AS "b" ,
--sum(case when strategy='c' then pnl else 0 end) AS "c"
--generate the contect above, (when using the code above the function works)
(SELECT string_agg(clause, ',')
FROM (SELECT format('sum(case when strategy=''%s'' then pnl else 0 end) AS "%s" ',
strategy, strategy) AS clause
FROM (SELECT DISTINCT strategy FROM server_logs.logs where strategy != '' and subclass = 'pnl') s
ORDER BY strategy) clauses)
FROM (
select case when strategy is null then 'system' else strategy end as strategy,
time,
sum(case when value::float!=0 then 0::float else value::float end) as pnl
FROM server_logs.logs
where subclass='pnl'
group by rollup(strategy), time
) as t
group by time
order by time desc
;