sql - 如何对 string_agg() 的结果进行排序

标签 sql postgresql string-aggregation

我有一张 table :

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_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

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

我正在使用 PostgreSQL 9.2.4。

最佳答案

使用 postgres 9.0+ 你可以写:

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

Details here .

关于sql - 如何对 string_agg() 的结果进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24906826/

相关文章:

mysql - SQL 查询不工作,使用 ideone。似乎无法发现错误。请额外的眼睛。 (简单查询)

postgresql - 如何在 Google Cloud 上的 Kubernetes 中备份 Postgres 数据库?

sql - Oracle:将子查询中的多个结果合并为一个逗号分隔的值

sql - PL/SQL 等效于 T-SQL 面向集合的变量串联

sql - Oracle 批量收集问题

c# - 如何制定 GroupJoin() 声明

sql - 如何知道应该在哪里使用 AS 关键字?

postgresql - 如何从 1 行中选择具有多行输出的数据(PostgreSQL)

javascript - KnexJS 外键约束中的种子表

甲骨文函数 : Replicate wm_concat