I have a database table:

```
| id | account | extra_account | state |special_value

```

I need to select extra\_accounts, which are connected with a list of accounts.

```
SELECT * FROM table
WHERE table.account in (111, 222, 333) and table.state = 'WORKS';

```

```none
|id  | account         | extra_account     | state         |special_value
—-------------------------------------------------------------------------------
|100 |111              |111-1              |WORKS          |1
|200 |111              |111-2              |WORKS          |1
|300 |222              |222-1              |WORKS          |2
|400 |333              |333-1              |WORKS          |3
|500 |333              |333-2              |WORKS          |4

```

I have to concatenate extra\_accounts in one String separated by a comma.

If an account has two or more extra\_accounts and their special\_value are the same I have to take one extra\_accounts, no matter which.
So for `id=100` and `id=200` I have to take just one extra\_account - 111-1 or 111-2, as their special\_values are equal.

If an account has two or more extra\_accounts and their special\_value are different I have to take all of them.
So for `id=400` and `id=500`, I need both - 333-1 and 333-2, as their special\_values are 3 and 4.

The final result should be:

```
|string_agg
|text
—----
|111-1, 222-1, 333-1, 333-2

```

I know that I can concat values by using:

```
SELECT  string_agg(table.extra_account, ', ')
FROM table WHERE table.account in (111, 222, 333) and table.state = 'WORKS';

```

But I didn’t find a way to select all rows if special\_values are different and only one row if special\_values are equal.