sql - 带条件的 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
,尽管我不建议存储此派生信息:相反,您可以创建一个视图,或在原始表中添加计算列。
推荐阅读
- algorithm - 如何在两个集合之间交换数据时降低运行时复杂性
- c++ - 将变量更改为串行监视器的文本(Arduino Uno)
- jquery - isotope : 过滤多个数据属性和seelect
- python - 如何从字典的元素信息中提取
- git - Sourcetree:将分支与新的子模块合并
- mysql - MySQL查询返回未定义-NodeJS
- stream - 在 Akka Streams 中使用 TTL 管理状态
- python - 错误:使用 heroku CLI 部署 Python 应用程序
- swift - 如何让我的 CustomView 返回 View 以及 SwiftUI 中的更多额外数据?
- c# - 将 Excel 单元格区域转换为 DataTable C#