Подтвердить что ты не робот

Как отсортировать результат от 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.

4b9b3361

Ответ 1

С postgres 9. 0+ вы можете написать:

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

Подробности здесь.

Ответ 3

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

SQL FIDDLE