2017-09-16 69 views
1

在Postgres的9.x中我可以这样做PostgreSQL的创建骨料与秩序和默认参数

select dept_id, string_agg(user_id, ':' order by user_id) 
from dept_user 
group by dept_id; 
+---------+------------+ 
| dept_id | string_agg | 
+---------+------------+ 
| d1  | u1:u2:u3 | 
| d2  | u3:u4  | 
+---------+------------+ 

但我的公司使用的Postgres 8.3,所以我觉得一个聚合函数可以像string_agg

create schema WMSYS; 
create or replace function WMSYS.sf_concat(text,text) returns text as $$ 
    select case when coalesce($1, '') <> '' then $1||','||$2 else $2 end; 
$$ language sql called on null input; 
create aggregate WMSYS.wm_concat (text) (sfunc=WMSYS.sf_concat,stype=text); 

结果是:

select dept_id, WMSYS.wm_concat(user_id) 
from dept_user 
group by dept_id; 
+---------+-----------+ 
| dept_id | wm_concat | 
+---------+-----------+ 
| d1  | u3,u1,u2 | 
| d2  | u3,u4  | 
+---------+-----------+ 

但结果是没有排序(u3,u1,u2应该是u1,u2,u3)并且连接字符串(,)不是参数。 我希望像这样使用:

WMSYS.wm_concat(user_id)   ## join by ',' and don't sort 
WMSYS.wm_concat(user_id, ':')  ## join by ':' and don't sort 
WMSYS.wm_concat(user_id, ':', true) ## join by ':' and order by user_id 

该怎么做?

+0

https://stackoverflow.com/a/2561297/330315和https://stackoverflow.com/q/16455483/330315 –

回答

1

试试这个:

准备数据样本:

t=# create table a1 (i int, t text); 
CREATE TABLE 
t=# insert into a1 select 1,'u'||g from generate_series(1,9,1) g; 
INSERT 0 9 
t=# update a1 set i =2 where ctid > '(0,4)'; 
UPDATE 5 
t=# select i,WMSYS.wm_concat(t) from a1 group by i; 
i | wm_concat 
---+---------------- 
1 | u1,u2,u3,u4 
2 | u5,u6,u7,u8,u9 
(2 rows) 

只是添加另一种说法:

create or replace function WMSYS.sf_concat(text,text,text) returns text as $$ 
    select case when coalesce($1, '') <> '' then $1||$3||$2 else $2 end; 
$$ language sql called on null input; 

create aggregate WMSYS.wm_concat (text,text) (sfunc=WMSYS.sf_concat,stype=text); 

t=# select i,WMSYS.wm_concat(t,':') from a1 group by i; 
i | wm_concat 
---+---------------- 
1 | u1:u2:u3:u4 
2 | u5:u6:u7:u8:u9 
(2 rows) 

现在,我不知道知道窗口函数将如何ORK在8.3和我没有包膜尝试,如果这样会工作:

t=# select i, max(t) from (select i,WMSYS.wm_concat(t,':') over (partition by i order by t desc) t from a1) a group by i; 
i |  max 
---+---------------- 
1 | u4:u3:u2:u1 
2 | u9:u8:u7:u6:u5 
(2 rows) 

但罗马曾建议,这应该:

t=# select i,WMSYS.wm_concat(t,':') from (select * from a1 order by i asc,t desc) a group by i; 
i | wm_concat 
---+---------------- 
1 | u4:u3:u2:u1 
2 | u9:u8:u7:u6:u5 
(2 rows) 

所以你操控的排序不作为参数传递给聚合函数,但用你提交数据的方式

0

请尝试:

SELECT dept_id, replace(WMSYS.wm_concat(user_id, ',', ':') 
    FROM (
     SELECT dept_id, user_id 
      FROM dept_user 
     ORDER BY 1, 2 
     ) AS A 
GROUP BY dept_id; 
+0

这可以做我想做的,但我希望' WMSYS.wm_concat'有控制连接字符串和排序的参数,那么这个函数将很容易重用。 – lionyu

+0

警告。用这个解决方案'a,1'加上'b,2'是'a:1:b:2'而不是'a,1:b,2'。 –