在联合查询中将两行删除为单行

时间:2016-07-25 14:24:54

标签: postgresql

我有像 -

这样的查询
select id,fieldName as value1,'' as value2 from tableName
union 
select id,'' as value1,fieldName as value2 from tableName

它输出像 -

id  value1  value2
1           name
1   name  
2   abc      
2           abcx

但尝试将其显示为 -

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

任何人都可以建议我怎么做。 在这种情况下工作是不可行的。

1 个答案:

答案 0 :(得分: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)