当一列为null时,从其他列获取数据

时间:2016-06-29 11:08:53

标签: sql

希望你能提供帮助。没有显示整个查询,因为我不认为它是必需的但是想尝试查询以查看'street'中有空值,然后查看'free address'并将结果放在那里。我猜它涉及案例表达或concat

当前结果

SELECT

IdNum
street
free address

from ID


IdNum          street                  free address
  1          stack over flow               null
  2             null                   stack exchange
  3           downing street               null

必需结果 - 不需要显示注释免费地址栏,仅用于演示。

 IdNum          street                    free address
   1         stack over flow                  null
   2         stack exchange                stack exchange
   3         downing street                   null

非常感谢您的帮助

5 个答案:

答案 0 :(得分:2)

COALESCE()函数执行此操作:

SELECT IdNum,
       COALESCE(street, free_address) as street,
       free_address
FROM ID;

注意:ID是表格的奇怪名称,free address不是有效的列名称(因为空格)。

COALESCE()是ANSI标准函数,基本上可用于所有数据库。

答案 1 :(得分:1)

使用$ node > []+[] '' > {}+{} '[object Object][object Object]' > []+{} '[object Object]' > {}+[] 0 > []-[] 0 > {}-{} NaN > []-{} NaN > {}-[] -0 > []*[] 0 > {}*{} NaN > []*{} NaN > {}*[] ... ^C > []/[] NaN > {}/{} NaN > []/{} NaN > {}/[] SyntaxError: Invalid regular expression: missing / at Object.exports.createScript (vm.js:24:10) at REPLServer.defaultEval (repl.js:137:25) at bound (domain.js:250:14) at REPLServer.runBound [as eval] (domain.js:263:12) at REPLServer.<anonymous> (repl.js:392:12) at emitOne (events.js:82:20) at REPLServer.emit (events.js:169:7) at REPLServer.Interface._onLine (readline.js:210:10) at REPLServer.Interface._line (readline.js:546:8) at REPLServer.Interface._ttyWrite (readline.js:823:14) 功能,可以用您选择的替代方案替换COALESCE()值:

NULL

答案 2 :(得分:1)

您可以使用CASECOALESCE或(在SQL-Server中)ISNULL

SELECT IdNum,
       CASE WHEN street IS NULL THEN free_address ELSE street END as street,
       free_address
FROM ID;

SELECT IdNum,
       COALESCE(street, free_address) as street,
       free_address
FROM ID;

SELECT IdNum,
       ISNULL(street, free_address) as street,
       free_address
FROM ID;

答案 3 :(得分:1)

根据您使用的数据库,您可以使用ISNULLNVLIFNULLCOALESCE

在此处选择正确的:SQL NULL Functions at w3schools

答案 4 :(得分:0)

如果使用SQL Server

,可以使用以下命令
Select [IdNum], 
Case 
When [street] Is Null AND [free address] Is Not Null 
Then [free address] else [street] END As 'street',
[free address]
from ID