如何对 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');

如果我在 string_agg() tblproducts

 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。

原文由 Vivek S. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.4k
2 个回答

使用 postgres 9.0+,您可以编写:

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

详情在这里

原文由 Ihor Romanchenko 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

SQL 小提琴

原文由 Ilesh Patel 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进