【发布时间】:2022-01-22 20:48:09
【问题描述】:
我有一个数据库表:
| id | account | extra_account | state |special_value
我需要选择extra_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
我必须将 extra_accounts 连接到一个用逗号分隔的字符串中。
如果一个帐户有两个或多个 extra_accounts 并且它们的 special_value 相同,我必须使用一个 extra_accounts,无论哪个。
所以对于id=100 和id=200,我只需要使用一个extra_account - 111-1 或111-2,因为它们的special_value 是相等的。
如果一个帐户有两个或多个 extra_accounts 并且它们的 special_value 不同,我必须全部使用它们。
所以对于id=400 和id=500,我需要 - 333-1 和 333-2,因为它们的 special_values 是 3 和 4。
最终结果应该是:
|string_agg
|text
—----
|111-1, 222-1, 333-1, 333-2
我知道我可以使用以下方法连接值:
SELECT string_agg(table.extra_account, ', ')
FROM table WHERE table.account in (111, 222, 333) and table.state = 'WORKS';
但我没有找到一种方法来选择如果 special_values 不同的所有行,如果 special_values 相等则只选择一行。
【问题讨论】:
标签: sql postgresql aggregate