将多个列合并为一个包含多行的列

时间:2017-01-29 01:23:18

标签: sql postgresql union-all

在PostgreSQL中,如何将多个列合并为一列多行?

列都是布尔值,所以我想:

  • 仅过滤真值
  • 将真实值(1)替换为列名(A,B或C)

我有这张桌子:

ID   | A   | B   | C
1      0     1     0
2      1     1     0
3      0     0     1
4      1     0     1
5      1     0     0 
6      0     1     1

我想得到这张表:

ID   | Letter
1      B
2      A
2      B
3      C
4      A
4      C
5      A
6      B
6      C

4 个答案:

答案 0 :(得分:3)

我认为你需要这样的东西:

SELECT ID, 'A' as Letter FROM table WHERE A=1
UNION ALL
SELECT ID, 'B' as Letter FROM table WHERE B=1
UNION ALL
SELECT ID, 'C'as Letter FROM table WHERE C=1
ORDER BY ID, Letter 

答案 1 :(得分:1)

SELECT ID,
(CASE 
    WHEN TABLE.A = 1 then 'A' 
    WHEN TABLE.B = 1 then 'B'
    WHEN TABLE.C = 1 then 'C' 
    ELSE NULL END) AS LETTER
from TABLE

答案 2 :(得分:1)

你可以试试这个。

 insert into t2 select id, 'A' from t1 where A=1;
 insert into t2 select id, 'B' from t2 where B=1;
 insert into t2 select id, 'C' from t3 where C=1;

如果您关心订单,那么您可以这样做。

insert into t3 select id, letter from t2 order by id, letter;

答案 3 :(得分:0)

W / o UNION

您可以使用单个查询来获得所需的输出。Real time example

select id
    ,regexp_split_to_table((
            concat_ws(',', case 
                    when a = 0
                        then null
                    else 'a'
                    end, case 
                    when b = 0
                        then null
                    else 'b'
                    end, case 
                    when c = 0
                        then null
                    else 'c'
                    end)
            ), ',') l
from c1;

regexp_split_to_table() & concat_ws()