我有一个表,我想通过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
语法从此查询开始轻松创建新表,尽管我不建议存储此派生信息:相反,您可以创建视图或在原始表中添加计算列。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句