2017-09-16 70 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'。 –