Tenho a seguinte tabela:
timestamp | type | value | source
----------+------+-------+--------
2020-01-01| 1 | 10 | 2
2020-01-01| 2 | 20 | 2
2020-01-02| 1 | 5 | 4
2020-01-02| 2 | 6 | 3
2020-01-02| 5 | 4 | 3
2020-01-02| 4 | 8 | 1
Cada par timestamp
+ é único. type
Para cada timestamp
, pode haver um número variável de linhas (mas cada uma com um type
). value
e source
são os dados reais.
Agora eu gostaria de agregar timestamp
em um array json onde, para cada timestamp, as tuplas disponíveis ( type
, value
, ) são incluídas. source
Idealmente, algo como:
[
{
"2020-01-01": [{"type": 1, "value": 10, "source": 2}, {"type": 2, "value": 20, "source": 2}]
},
{
"2020-01-02": [{"type": 1, "value": 5, "source": 4}, {"type": 2, "value": 6, "source": 3}, {"type": 5, "value": 4, "source": 3}, {"type": 4, "value": 8, "source": 1}]
}
]
Eu realmente não tenho preferências fortes no formato de saída, desde que as informações estejam lá e agrupadas corretamente, então, por exemplo, isso também seria bom:
[
{
"timestamp": "2020-01-01", "data": [{"type": 1, "value": 10, "source": 2}, {"type": 2, "value": 20, "source": 2}]
},
{
"timestamp": "2020-01-02", "data": [{"type": 1, "value": 5, "source": 4}, {"type": 2, "value": 6, "source": 3}, {"type": 5, "value": 4, "source": 3}, {"type": 4, "value": 8, "source": 1}]
}
]
Ou isso (que eu acho que exigiria a conversão type
para string, o que não é um problema):
[
{
"timestamp": "2020-01-01", "1": {"value": 10, "source": 2}, "2": {"value": 20, "source": 2}
},
{
"timestamp": "2020-01-02", "1": {"value": 5, "source": 4}, "2": {"value": 6, "source": 3}, "5": {"value": 4, "source": 3}, "4": {"value": 8, "source": 1}
}
]
Mesmo isso, desde que a ordenação do campo seja conhecida com antecedência:
[
{
"2020-01-01": [[1, 10, 2], [2, 20, 2]]
},
{
"2020-01-02": [[1, 5, 4], [2, 6, 3], [5, 4, 3], [4, 8, 1]]
}
]
Em suma, o que for mais fácil/eficiente.
https://dbfiddle.uk/?rdbms=postgres_12&fiddle=2fc37233058437189b8e0a8eea05a01b