【问题标题】:How to sort the result from string_agg()如何对 string_agg() 的结果进行排序
【发布时间】:2014-09-14 10:07:00
【问题描述】:

我有一张桌子:

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。

【问题讨论】:

    标签: sql postgresql string-aggregation


    【解决方案1】:

    使用 postgres 9.0+ 你可以写:

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

    Details here.

    【讨论】:

    • 您能否提出一个在使用窗口函数时也可以使用的解决方案?
    • 感谢您的链接。在文档中搜索 string_agg 不会带你到那里。
    【解决方案2】:

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

    【讨论】:

    • 问题是关于 PostgreSQL。 WITHIN GROUP 子句不适用于string_agg 函数,它适用于 Microsoft SQL。
    • 问题是关于 string_agg。 Postgres 对他的问题很偶然,他最后提到了这个问题。这个问题对其他人也很有用。
    • 如果此语法给您带来语法错误,请检查您的兼容性级别:stackoverflow.com/questions/43611024/…
    【解决方案3】:
    select string_agg(prod,' | ') FROM 
      (SELECT product as prod FROM tblproducts ORDER BY product )MAIN;
    

    SQL FIDDLE

    【讨论】:

    • 我遇到了和 OP 一样的问题,这个方法是我的第一个想法,但不幸的是它不起作用(这把我带到了这里),而 Igor 的却是。
    • 就我而言,两种方法(Ilesh 和 Igor)都有效。
    • 错误答案。它可能有效,但不保证有效。
    • 关系数据库部分基于数学集,这反映在 SQL 的一个基本原则是行顺序不重要这一事实上。即使您要在子查询中包含 ORDER BY 子句,FROM 子句也不一定会按顺序获取数据。如果这行得通,那纯属运气。
    • 我很高兴使用这个解决方案很长一段时间,直到有一天一些数据进入我的系统导致它不再工作。这是非常具有欺骗性的。 (尽管为了 Ilesh 的辩护,文档确实说它“通常”会起作用:“或者,从排序的子查询中提供输入值通常会起作用”)
    猜你喜欢
    • 2014-01-08
    • 2021-06-29
    • 2015-01-12
    • 1970-01-01
    • 2021-08-25
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多