2016-07-25 27 views
0

我有查詢像 -工會查詢中刪除兩行分爲單列

select id,fieldName as value1,'' as value2 from tableName 
union 
select id,'' as value1,fieldName as value2 from tableName 

它給輸出like--

id value1 value2 
1   name 
1 name 
2 abc  
2   abcx 

而是試圖顯示它喜歡 -

id value1 value2 
1 name  name 
2 abc  abcx 
PostgreSQL中的

任何人都可以告訴我該怎麼辦。 是univot工作這種情況。

回答

2

使用string_agg()

select string_agg(value1, '') value1, string_agg(value2, '') value2 
from (
    select 'name' as value1, '' as value2 
    union 
    select '' as value1, 'name' as value2 
    ) s; 

value1 | value2 
--------+-------- 
name | name 
(1 row)  

聚合功能,如string_agg()通常爲行組執行。使用group by id

with a_table(id, col1, col2) as (
    values 
     (1, 'name', 'name'), 
     (2, 'abc', 'abcx') 
    ) 
select id, string_agg(value1, '') value1, string_agg(value2, '') value2 
from (
    select id, col1 as value1,'' as value2 from a_table 
    union 
    select id, '' as value1, col2 as value2 from a_table 
    ) s 
group by id 
order by id; 

id | value1 | value2 
----+--------+-------- 
    1 | name | name 
    2 | abc | abcx 
(2 rows)  
+0

如果名稱字段從數據庫(表)中選擇返回多個名字,在這種情況下所有的名字都是GET串聯與分隔符,顯示在一個row.but試圖顯示在每個名字不同行。 – Basavaraj

+0

查看編輯答案。 – klin

+0

謝謝you.it作品 – Basavaraj