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

Viv*_* S. 77 sql postgresql string-aggregation

我有一张桌子:

CREATE TABLE tblproducts
(
productid integer,
product character varying(20)
)
Run Code Online (Sandbox Code Playgroud)

随着行:

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');
Run Code Online (Sandbox Code Playgroud)

如果我执行string_agg()tblproducts:

SELECT string_agg(product, ' | ') FROM "tblproducts"
Run Code Online (Sandbox Code Playgroud)

它将返回以下结果:

CANDID POWDER 50 GM | ESOZ D 20 MG CAP | HHDERM CREAM 10 GM | CREAM 15 GM | KZ LOTION 50 ML | BUDECORT 200 Rotocap
Run Code Online (Sandbox Code Playgroud)

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

我正在使用PostgreSQL 9.2.4.

Igo*_*nko 184

使用postgres 9.0+,你可以写:

select string_agg(product,' | ' order by product) from "tblproducts"
Run Code Online (Sandbox Code Playgroud)

详细信息:http://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES


Luu*_*uuk 8

https://docs.microsoft.com/zh-cn/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT
  STRING_AGG(prod, '|') WITHIN GROUP (ORDER BY product)
FROM ... 
Run Code Online (Sandbox Code Playgroud)

  • 问题是关于 string_agg 的。Postgres 是他的问题的附带内容,他最后提到了这一点。这个问题对其他人也有用。 (24认同)
  • 问题是关于 PostgreSQL 的。与 Microsoft SQL 不同,WITHIN GROUP 子句不适用于 string_agg 函数。 (5认同)
  • 如果此语法给您带来语法错误,请检查您的兼容性级别:/sf/ask/3052771711/ (2认同)