Following on from [Combining array\_agg and unnest](https://dba.stackexchange.com/q/241989), 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](https://dba.stackexchange.com/a/242107) option 1: `1761.12..49370.52`
* [a\_horse\_with\_no\_name](https://dba.stackexchange.com/a/242107) option 2: `0.57..89214.72`
* [Erwin Brandstetter](https://dba.stackexchange.com/a/242111): `1761.12..49370.61`