I am trying to get Table Data in a vertical way using Crosstab. To be more precise, I need to group by prefix and postfix at the same time and get summ. In this case I should Join 2 tables and get names for unique prefix and postfix. Number of Columns may vary depending on income_account_setting table values. In my case I have more than 20 different names meaning that I should have code_account and 20 columns. I tried to do with the help of Crosstab, But on the internet examples are given for fixed number of columns
My Tables: main_client_profit
id | code_account | summa | prefix | postfix | oper_month |
------------------------------------------------------------------------------------
1 | 04315187 | 72871232.77 | 45233 | 222 | 2020-04 |
2 | 00524154 | 89753426.58 | 45294 | 100 | 2020-01 |
3 | 02115187 | 23224345.89 | 45249 | 204 | 2020-03 |
4 | 00388996 | 119030.87 | 45294 | 246 | 2020-05 |
5 | 04222959 | 105000.00 | 45233 | 222 | 2020-04 |
6 | 04315187 | 92871232.77 | 45233 | 222 | 2020-04 |
1 | 04222959 | 1020458.40 | 45233 | 421 | 2020-01 |
income_account_setting
id | prefix | postfix | name |
-------------------------------------------------------------------------------------
1 | 45233 | 222 | A |
1 | 45294 | 100 | B |
1 | 45249 | 204 | C |
1 | 45294 | 246 | E |
1 | 45233 | 421 | F |
The result I need to take
------------------------------------------------------------------------------------
code_account | A | B | C | D | E |
----------------------------------------------------------
04315187 | 165742465 | 0 | 0 | 0 | 0 |
00524154 | | 89753426.58 | 0 | 0 | 0 |
02115187 | 0 | | 23224345.89 | 0 | 0 |
and etc ....
What I tried so far but it does not work
SELECT *
FROM crosstab('SELECT m.code_account, a.name, evaluation_result
FROM main_client_profit m
INNER JOIN income_account_setting a
ON m.prefix = a.prefix AND m.postfix = a.postfix
GROUP BY CONCAT(m.prefix,m.postfix)
ORDER BY 1,2')
AS final_result(code character varying(20),)
In above code I don`t know what to write inside final_result as columns.
Is it possible to do this task with Crosstab? Or is there any other way to do it Any help is appreciated.