首页 > 解决方案 > 带条件的 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

提前致谢。

标签: sqlstringdatatables

解决方案


您可以使用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,尽管我不建议存储此派生信息:相反,您可以创建一个视图,或在原始表中添加计算列。


推荐阅读