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
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)
| 归档时间: |
|
| 查看次数: |
72907 次 |
| 最近记录: |