如何从 string_agg()对结果进行排序

我有一张桌子:

CREATE TABLE tblproducts
(
productid integer,
product character varying(20)
)

有排的:

INSERT INTO tblproducts(productid, product) VALUES (1, 'CANDID POWDER 50 GM');
INSERT INTO tblproducts(productid, product) VALUES (2, 'SINAREST P SYP 100 ML');
INSERT INTO tblproducts(productid, product) VALUES (3, 'ESOZ D 20 MG CAP');
INSERT INTO tblproducts(productid, product) VALUES (4, 'HHDERM CREAM 10 GM');
INSERT INTO tblproducts(productid, product) VALUES (5, 'CREAM 15 GM');
INSERT INTO tblproducts(productid, product) VALUES (6, 'KZ LOTION 50 ML');
INSERT INTO tblproducts(productid, product) VALUES (7, 'BUDECORT 200 Rotocap');

如果我在 tblproducts上执行 string_agg():

SELECT string_agg(product, ' | ') FROM "tblproducts"

它将返回以下结果:

CANDID POWDER 50 GM | ESOZ D 20 MG CAP | HHDERM CREAM 10 GM | CREAM 15 GM | KZ LOTION 50 ML | BUDECORT 200 Rotocap

如何按照使用 ORDER BY product得到的顺序对聚合的字符串进行排序?

我使用的是 PostgreSQL 9.2.4。

151994 次浏览
select string_agg(prod,' | ') FROM
(SELECT product as prod FROM tblproducts ORDER BY product )MAIN;

SQL FIDDLE

用 postgres 9.0 + 你可以写:

select string_agg(product,' | ' order by product) from "tblproducts"

详情请浏览此处

对于 MicrosoftSQL: 使用“ WITHINGROUP”

Https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT
STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product)
FROM ...

即使在选角时,这似乎也是按数字排序的:

select string_agg(cast (o.id as varchar),',' order by o.id) from tb_organisation o
inner join tb_country c on o.country_fk = c.id
where c.name ilike '%united%' group by c.id;