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';
|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.