The following bug has been logged on the website:
Bug reference: 18757
Logged by: CangSheng Shen
Email address: shencangsheng@126.com
PostgreSQL version: 13.9
Operating system: MacOS
Description:
string_agg function(text, text) design issue
```sql
create table users (
id SERIAL PRIMARY KEY,
name character varying(100),
no integer
);
select
name,
string_agg(no::text, ',' order by no asc) as nos
from
users
group by name;
```
When I require distinct, I cannot continue using no for sorting; instead, I
need to use no::text, otherwise I will encounter the exception: `in an
aggregate with DISTINCT, ORDER BY expressions must appear in argument
list.`
```sql
select
name,
string_agg(no::text, ',' order by no::text asc) as nos
from
users
group by name;
```
This results in incorrect sorting and does not meet expectations.
Could you optimize `string_agg` or suggest an alternative function to handle
such a scenario?