将来自多个列的数据合并为一个

时间:2018-03-05 12:41:08

标签: sql

我有三列X,Y& Z.我想做一个只返回一列的select语句。 例如,对于以下行:

X Y Z
1 0 0 
0 1 0
0 0 1

我想返回一列A:

A
X 
Y
Z

因此,只要有一个列,该列应该返回一个对应于列名的字符串,它是一个...

我没有权利在数据库中创建新列,然后使用where条件更新它。所以我想知道它是否可以在SELECT语句中完成

4 个答案:

答案 0 :(得分:3)

不处理一行中的多个1值:

select case
         when x = 1 then 'X' 
         when y = 1 then 'Y'
         when z = 1 then 'Z'
       end as A
from the_table;

如果您正在使用Postgres并在该表上具有主键列,则可以使用JSON函数使其动态化,而不是对查询中的列名进行硬编码。

测试数据设置:

create table the_table (id integer, x int, y int, z int);
insert into the_table 
  (id,x,y,z)
values
  (1, 1, 0, 0), 
  (2, 0, 1, 0),
  (3, 0, 0, 1),
  (4, 0, 1, 1),
  (5, 0, 0, 0);

然后使用此查询:

select t.id, string_agg(k.col,'' order by k.col) as non_zero_columns
from the_table t, 
     jsonb_each(to_jsonb(t) - 'id') as k (col, val)
where k.val = '1'
group by id
order by id;

将返回此结果:

id | non_zero_columns
---+-----------------
 1 | x               
 2 | y               
 3 | z               
 4 | yz              

请注意,不会返回ID = 5的行,因为所有列都为零。

答案 1 :(得分:1)

如果您在一行中有多个列为1的列:

select ((case when x = 1 then 'X' else '' end) ||
        (case when y = 1 then 'Y' else '' end) ||
        (case when z = 1 then 'Z' else '' end)
       ) as A
from the_table;

请注意,||是字符串连接的ANSI标准运算符。有些数据库使用其他方法来连接字符串。

答案 2 :(得分:0)

如果您使用的是ms sq-server,则可以使用UNPIVOT

DECLARE @MyTable TABLE (X INT, Y INT, Z INT)
INSERT INTO @MyTable VALUES
(1 ,0, 0 ),
(0 ,1, 0 ),
(0 ,0, 1 )

SELECT DISTINCT A FROM 
    (select * from @MyTable UNPIVOT( V FOR A IN ([X], [Y], [Z])) UNPVT) UP
WHERE V = 1

结果:

A
---------
X
Y
Z

答案 3 :(得分:-1)

您可以将INFORMATION_SCHEMAfind_in_set(str, strlist)函数(MySql)一起使用:

-- the schema
create table `docs` (
  `X` int not null,
  `Y` int not null,
  `Z` int not null
);
insert into `docs` (`X`, `Y`, `Z`) values
  (1, 0, 0),
  (0, 1, 0),
  (0, 0, 1);

-- the query
select column_name as A, concat(x, y, z)
from docs
join INFORMATION_SCHEMA.COLUMNS
on (ordinal_position = find_in_set('1', concat(x, ',', y, ',', z)))
where table_name like 'docs';

此处为SQL Fiddle

相关问题