Fra din nuværende tilstand kan du ganske enkelt foretage pivoten ved hjælp af FILTER
klausul:
SELECT
response,
document,
MAX(bill) FILTER (WHERE label = 'bill') as bill,
MAX(answer) FILTER (WHERE label = 'amount') as amount,
MAX(product) FILTER (WHERE label = 'product') as product,
MAX(answer) FILTER (WHERE label = 'price') as price
FROM t
GROUP BY response, document
Jeg er ikke helt sikker på, hvordan dit originale bord ser ud. Hvis det er mere sådan her:
response | document | label | value
-------: | -------: | :------ | :----
71788176 | 79907201 | bill | 26899
71788176 | 79907201 | amount | 1
71788176 | 79907201 | product | shoes
71788176 | 79907201 | price | 25.99
Derefter kan du ændre forespørgslen sådan her:
SELECT
response,
document,
MAX(value) FILTER (WHERE label = 'bill') as bill,
MAX(value) FILTER (WHERE label = 'amount') as amount,
MAX(value) FILTER (WHERE label = 'product') as product,
MAX(value) FILTER (WHERE label = 'price') as price
FROM t
GROUP BY response, document
Rediger :FOR AT tilføje JSON-værdien til produktkolonnen:
Variant 1:Du kan simpelthen caste typen json
ind i text
:
MAX(product::text) FILTER (WHERE label = 'product') as product,
Variant 2:Du læser værdien fra "name"
attribut:
MAX(product ->> 'name') FILTER (WHERE label = 'product') as product,