【发布时间】:2021-06-16 16:14:46
【问题描述】:
我有一个有 2 列的表格。如果行仅包含第 1 列的值,那么我需要执行操作 a。如果它对两列都有值,我需要执行操作 b,如果行只有第 2 列,我需要执行操作操作 3。如何为此编写 SQL
【问题讨论】:
-
什么数据库?是您要执行的操作吗?应用程序端的命令/查询或其他东西?到目前为止,您尝试过什么?
我有一个有 2 列的表格。如果行仅包含第 1 列的值,那么我需要执行操作 a。如果它对两列都有值,我需要执行操作 b,如果行只有第 2 列,我需要执行操作操作 3。如何为此编写 SQL
【问题讨论】:
尝试创建一个返回 table 的函数,满足所有条件。在步骤中维护一个表变量(比如@tab1),将中间值插入到该表(或追加),最后返回该变量。
这样你就可以在 sql 查询中使用这个函数
【讨论】:
如果“操作”是指“在结果集中的列中设置一个值”,那么您需要一个 case 表达式:
select (case when col1 is not null and col2 is null then 'a'
when col1 is not null and col2 is not null then 'b'
when col1 is null and col2 is not null then 'c'
end)
from t;
【讨论】: