Question: I have a table `x` which have the fields `a`, `b`, `c`, and `d`. I want to do a **SELECT** statement which is **GROUPED BY** `a` **HAVING** a\_particular\_value = **ANY**(array\_agg(`b`)) and **retrieves** `a`, **MIN**(`d`), and `c` <- from which row is chosen by `a_particular_value = ANY(array_agg(b))`.
It's a bit confusing.

Lemme try to explain. `a_particular_value = ANY(array_agg(b))` will choose some or one record from all records that is grouped by `a`. I want to retrieve the value of `c` from the record that causes the condition to be true. While NOT filter out other records because I still need those for the other aggregate function, `MIN(d)`.

The query that I've tried to make:

```
SELECT a, MIN(d) FROM x
GROUP BY a
HAVING 1 = ANY(array_agg(b))

```

The only thing that's left to do is put `c` in the **SELECT** clause. How do I do this?

Answer: 
```
with agg as (
    select a, min(d) as d
    from x
    group by a
    having 1 = any(array_agg(b))
)
select distinct on (a, c)
    a, c, d
from
    x
    inner join
    agg using (a, d)
order by a, c

```

If `min(d)` is not unique within the `a` group then it is possible to exist more than one corresponding `c`. The above will return the smallest c. If you want the biggest do in instead

```
order by a, c desc

```
`c` can have various values in this scenario, so your only option is to group by `c` as well.

```
SELECT a, c FROM x
GROUP BY a, c
HAVING 1 = ANY(array_agg(b))

```

If you want to eliminate rows with `b` not satisfying condition before applying `GROUP BY` then use `WHERE` as documentation for `HAVING` says <http://www.postgresql.org/docs/9.2/static/sql-select.html#SQL-HAVING>