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

时间:2014-07-23 09:30:31

标签: postgresql string-aggregation

我有一张桌子:

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。

3 个答案:

答案 0 :(得分:161)

使用postgres 9.0+,你可以写:

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

Details here

答案 1 :(得分:6)

https://docs.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 ... 

答案 2 :(得分:4)

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

SQL FIDDLE