I have a query who returns the next results
+-----------+--------+-------+
| idPeriodo | codigo | valor |
+-----------+--------+-------+
| 1 | 7 | 1000 |
| 1 | 8 | 1000 |
| 1 | 9 | 1000 |
| 2 | 7 | 1000 |
| 2 | 8 | 1000 |
| 3 | 7 | 1000 |
| 3 | 9 | 1000 |
+-----------+--------+-------+
I need to organize the query because I'm creating a text plain file with the results, so in the first row I need to put each "codigo" split by tab, something like this.
--This is the first row, is like a head
7 8 9
Afther this, I need to put the column "valor" associated with its respective codigo and idPeriodo. The final result must be something like this:
7 8 9
1 1000 1000 1000
2 1000 1000
3 1000 1000
Now I have two queries, the first one is to obtain the first row(head with codigo values) and second one I'm doing a query to obtain all values from column "valor" grouped by idPeriodo. These are my queries looks like.
-------Query to return head(codigo values)---------------
SELECT DISTINCT CONCAT(conjunto.codigo, central.confterm_id) as codigo_central
FROM mantenimiento_central_termica mantenimiento
JOIN configuracion_central_termica central
ON central.confterm_id = mantenimiento.confterm_id
JOIN conjunto_centrales conjunto
ON central.id_conjuntocentral = conjunto.id
-------Query to return valor grouped by idPeriodo---------------
SELECT id_periodo ,
valor_mantenimiento = string_agg(valor_mantenimiento, CHAR(9))
WITHIN GROUP (ORDER BY codigo_central)
FROM(
SELECT CONCAT(conjunto.codigo, central.confterm_id) as codigo_central,
per_id AS id_periodo ,
mantenimcentraltermica_potencia AS valor_mantenimiento
FROM mantenimiento_central_termica mantenimiento
JOIN configuracion_central_termica central
ON central.confterm_id = mantenimiento.confterm_id
JOIN conjunto_centrales conjunto
ON central.id_conjuntocentral = conjunto.id
WHERE cas_id = 2) main_thermal
GROUP BY id_periodo
The problem I have is the second query returns only the values from column valor who is not null and when I'm going to split the first query with the second one I obtain something like this:
7 8 9
1 1000 1000 1000
2 1000 1000
3 1000 2000 --The error is here, because the 2000 value must be in the third column, with the 9(codigo) value.
I need the query put a blank space when find a null valor in a relation between codigo and idPeriodo.
How Can i do that ?