2015-09-18 50 views
0

我有一個ID爲表的組名映射。創建CSV文件時在Postgres ID到數組中的名稱映射

1. GroupA 
2. GroupB 
3. GroupC 
. 
. 
. 
15 GroupO 

我必須跟用戶id到組ID映射用戶表中,組ID在用戶表中定義爲陣列

User1 {1,5,7} 
User2 {2,5,9} 
User3 {3,5,11,15} 
. 
. 
. 

我想以這樣的方式結合到表以檢索用戶ID和組名以CSV文件進行映射。

例如:用戶1 {A組,陽獅集團,GroupG}

本質組ID應該得到按組名稱替換在創建CSV文件。

+1

@TimBiegeleisen:我覺得他寫一個CSV文件,該表顯示存儲在'integer []'列中的組ID(這很好,並且由PostgreSQL支持)。 –

+0

是的,這就是我所做的! – Pravin

回答

2

設置:

create table mapping(id int, group_name text); 
insert into mapping 
select i, format('Group%s', chr(i+ 64)) 
from generate_series(1, 15) i; 

create table users (user_name text, user_ids int[]); 
insert into users values 
('User1', '{1,5,7}'), 
('User2', '{2,5,9}'), 
('User3', '{3,5,11,15}'); 

一步一步(理解查詢,看SqlFiddle):

使用UNNEST()列出所有單一的user_id在一排:

select user_name, unnest(user_ids) user_id 
from users 

通過加入映射來替換group_name中的user_id:

select user_name, group_name 
from (
    select user_name, unnest(user_ids) id 
    from users 
    ) u 
join mapping m on m.id = u.id 

骨料組名成數組USER_NAME:

select user_name, array_agg(group_name) 
from (
    select user_name, group_name 
    from (
     select user_name, unnest(user_ids) id 
     from users 
     ) u 
    join mapping m on m.id = u.id 
    ) m 
group by 1 

使用拷貝命令的最後一個查詢:

copy (
select user_name, array_agg(group_name) 
from (
    select user_name, group_name 
    from (
     select user_name, unnest(user_ids) id 
     from users 
     ) u 
    join mapping m on m.id = u.id 
    ) m 
group by 1 
) 
to 'c:/data/example.txt' (format csv) 
2

假設你有這種形式的兩個表:

Table groups 
Column | Type 
-----------+--------- 
groupname | text  
groupid | integer 

Table users 
Column | Type  
----------+---------- 
username | text  
groupids | integer[] <-- group ids as inserted in table groups 

您可以查詢用戶使用此代碼替換爲組名組ID:

WITH users_subquery AS (select username,unnest (groupids) AS groupid FROM users) 
SELECT username,array_agg(groupname) AS groups 
FROM users_subquery JOIN groups ON users_subquery.groupid = groups.groupid 
GROUP BY username 

如果您需要的羣體作爲字符串(對csv導出有用),用array_to_string語句括住查詢:

SELECT username, array_to_string(groups,',') FROM 
(
    WITH users_subquery AS (select username,unnest (groupids) AS groupid FROM users) 
    SELECT username,array_agg(groupname) AS groups 
    FROM users_subquery JOIN groups ON users_subquery.groupid = groups.groupid 
    GROUP BY username 
) as foo; 

結果:

username | groups  
----------+----------------- 
user1 | group1,group2 
user2 | group2,group3 
相關問題