Following on from Combining array_agg and unnest, given this data:
key | a | b | c
------------------
1 | 0 | 1 | {1,2}
1 | 1 | 2 | {3}
1 | -1 | 3 | {2}
1 | 2 | 4 | {}
Executing this query:
SELECT
d.key,
min(d.a) AS a,
sum(d.b) AS b,
array_agg(DISTINCT x.c) AS c
FROM data AS d
CROSS JOIN LATERAL unnest(d.c) AS x(c)
GROUP BY d.key
Gives the unexpected result:
key | a | b | c
------------------
1 | -1 | 7 | {1,2,3}
What's going on here, and how to get the correct sum?
Answer performance
On my actual data (16642 rows, 1942 keys, 6 aggregates), I get these cost estimates for each suggested solution.
- a_horse_with_no_name option 1:
1761.12..49370.52
- a_horse_with_no_name option 2:
0.57..89214.72
- Erwin Brandstetter:
1761.12..49370.61
explain (analyze, buffers)
is the interesting thing - but this is the price you pay for not normalizing properly – a_horse_with_no_name Jul 5 '19 at 4:59