Dari kondisi Anda saat ini, Anda cukup melakukan pivot menggunakan FILTER
klausa:
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
Saya tidak yakin, bagaimana tampilan tabel asli Anda. Jika lebih seperti ini:
response | document | label | value
-------: | -------: | :------ | :----
71788176 | 79907201 | bill | 26899
71788176 | 79907201 | amount | 1
71788176 | 79907201 | product | shoes
71788176 | 79907201 | price | 25.99
Kemudian Anda dapat memodifikasi kueri seperti ini:
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
Sunting :UNTUK menambahkan nilai JSON ke kolom produk:
Varian 1:Anda cukup menggunakan tipe json
ke dalam ketik text
:
MAX(product::text) FILTER (WHERE label = 'product') as product,
Varian 2:Anda membaca nilai dari "name"
atribut:
MAX(product ->> 'name') FILTER (WHERE label = 'product') as product,