Sql 如何对字符串_agg()中的结果进行排序

Sql 如何对字符串_agg()中的结果进行排序,sql,postgresql,string-aggregation,Sql,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')

我有一张桌子:

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\u 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
如何按照使用
orderbyproduct
获得的顺序对聚合字符串进行排序

我正在使用PostgreSQL 9.2.4

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

使用postgres 9.0+你可以写:

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


我和OP有同样的问题,这种方法是我的第一个想法,但不幸的是它不起作用(这让我来到这里),而Igor的起作用。在我这方面,两种方法(Ilesh和Igor)都起作用。回答错误。关系数据库部分基于数学集,这反映在SQL的一个基本原则是行顺序不重要。即使要在子查询中包含一个
orderby
子句,
FROM
子句也不一定按顺序获取数据。如果这能起作用,那纯粹是运气。你能建议一个在使用窗口功能时也能起作用的解决方案吗?谢谢你的链接。在文档中搜索
string\u agg
不会让您达到目的。问题是关于PostgreSQL的。组内
子句不适用于
string\u agg
函数,与Microsoft SQL一样。问题是关于string\u agg的。博士后的问题是偶然的,他最后提到了。此问题对其他人也很有用。如果此语法导致语法错误,请检查您的兼容性级别:
SELECT
  STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product)
FROM ...