![](/img/trans.png)
[英]In postgres, how to sort on, among others, a result value of a string_agg function, without selecting that field? Subquery not possible
[英]How to sort the result from string_agg()
我有一张桌子:
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。
对于 Microsoft SQL:使用“WITHIN GROUP”
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 ...
select string_agg(prod,' | ') FROM
(SELECT product as prod FROM tblproducts ORDER BY product )MAIN;
即使使用强制转换,这似乎也是按数字排序的:
select string_agg(cast (o.id as varchar),',' order by o.id) from tb_organisation o
inner join tb_country c on o.country_fk = c.id
where c.name ilike '%united%' group by c.id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.