SQL带有条件的新表



我有一个表,我想通过sql将它解析成另一个表。问题在于存在一个条件:旧版本中有3列

column_1 column_2 column_3
0            1      1
1            0      1
1            1      1

我想把它们存储到新表的列中,比如:

new_column_1
no/yes/yes
yes/no/yes
yes/yes/yes

提前谢谢。

您可以使用case表达式和字符串串联,如下所示:

select t.*,
(case when column_1 = 1 then 'yes' else 'no' end)
|| '/' || (case when column_2 = 1 then 'yes' else 'no' end)
|| '/' || (case when column_3 = 1 then 'yes' else 'no' end) as new_column_1
from mytable t

这使用了标准的字符串串联运算符||;一些数据库具有另一个运算符或函数。

一些数据库还支持concat_ws(),这稍微简化了表达式:

select t.*,
concat_ws('/', 
(case when column_1 = 1 then 'yes' else 'no' end)
(case when column_2 = 1 then 'yes' else 'no' end)
(case when column_3 = 1 then 'yes' else 'no' end)
) as new_column_1
from mytable t

您可以使用insert ... select语法从这个查询开始轻松地创建一个新表,尽管我不建议存储这些派生信息:相反,您可以创建一个视图,或者在原始表中添加计算列。

最新更新