将2列组合成一列SQL

时间:2016-03-28 18:52:06

标签: sql postgresql

我是Postgres的初学者,需要做这样的事情。 我的Postgres查询输出有2列。我需要将这两者结合起来,如下所示。

第1栏:

A
B
C

第2栏:

D
D
D

输出栏:

A
B
C
D

(第1列的所有值和第2列的不同值)

这在PostgreSQL中是否可行?

4 个答案:

答案 0 :(得分:4)

嗨,有一种奇特的方式:

select distinct unnest(array[
        column1
        , column2
    ])
from table

答案 1 :(得分:0)

你需要这样的东西:

 select  col    from (
   select Column1 as col   from <your table >
    union all 
    select distinct Column2 as col   from <your table>
) as myview order by col 

答案 2 :(得分:0)

将原始查询放入公用表表达式,然后汇总每列的不同值:

with data (fromzoneid, fromzoneid2) as ( 
  ... your complete original query goes here ...
)
select string_agg(distinct c1, '') as zoneid
from (
  select t1.c1
  from data
    cross join regexp_split_to_table(fromzoneid, '') as t1 (c1)
  union 
  select t2.c1
  from data
    cross join regexp_split_to_table(fromzoneid2, '') as t2 (c1)
)  t;

注意

以上假设您的查询只返回一行。我的解决方案将汇总查询返回的所有行的值!如果查询返回的行多于行,则所有行的唯一字符将合并为一列和单行!

如果您不想这样,您需要在查询中添加一个可用于按语句分组的列

类似的东西:

with data (id, fromzoneid, fromzoneid2) as ( 
  ... your complete original query goes here ...
)
select id, string_agg(distinct c1, '') as zoneid
from (
  select data.id, t1.c1
  from data
    cross join regexp_split_to_table(fromzoneid, '') as t1 (c1)
  union 
  select data.id, t2.c1
  from data
    cross join regexp_split_to_table(fromzoneid2, '') as t2 (c1)
)  t
group by id

答案 3 :(得分:0)

我遇到了同样的问题。我有3个列并希望将行组合成一个并且不需要重复的值。因为我在第一步中通过col1 || '#' || col2 || '#' || col3合并了它们。然后我使用string_to_array函数将字符串拆分为数组,以便在最后一步使用unnest。毕竟我可以使用DISTINCT覆盖我的结果。

SELECT DISTINCT unnest(string_to_array(col1 || '#' || col2 || '#' || col3, '#')) FROM my_table;
相关问题