By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
CREATE TABLE
INSERT 0 4
CREATE TABLE
INSERT 0 9
| stmt |
|---|
| SELECT * FROM crosstab( $$SELECT DISTINCT ON (1, 2) j.reference, 'subj_'||j.subj||'_'||s.name AS data_type, SUM(j.value) AS val FROM Journal j JOIN Subject s ON s.id = j.subj GROUP BY j.reference, j.subj, s.name ORDER BY j.reference$$ ,$$VALUES ('subj_1_fruit'), ('subj_2_drink'), ('subj_3_vege'), ('subj_4_fish')$$) AS x (reference text, subj_1_fruit int, subj_2_drink int, subj_3_vege int, subj_4_fish int) |
SELECT 1
| reference | subj_1_fruit | subj_2_drink | subj_3_vege | subj_4_fish |
|---|---|---|---|---|
| bar | 45 | 25 | null | 40 |
| baz | 20 | 25 | null | null |
| foo | 30 | null | null | 30 |
SELECT 3