【问题标题】:SQL: Is there a way for me to call another table.field when my initial table.field = NULL?SQL:当我的初始 table.field = NULL 时,我有没有办法调用另一个 table.field?
【发布时间】:2020-12-07 18:01:55
【问题描述】:

大家早上好!本质上,我发现我想使用的潜在 table.field 可能没有我想要的信息,所以我可能不得不查看一个单独的字段。我下面的思考过程是:

If table.field1 = NULL then pull the value from table.field2. If table.field2 = NULL then state "No Phone"

我当前在select中的sql语句,由于是某种格式,是:

substring(view_episode_summary_current.patient_home_phone, 1, 3) || ' ' || substring(view_episode_summary_current.patient_home_phone, 5, 8)

上面是table.field1。我假设我需要创建一个 CASE 语句,对吗?就是不知道要多久?

(case when view_episode_summary_current.patient_home_phone = NULL then table.field2)

但我不知道如何让它评估 if table.field2 = null 并显示该值。

【问题讨论】:

    标签: sql sql-null


    【解决方案1】:

    在许多数据库中,您可以使用coalesce() 来实现这种逻辑:

    coalesce(t1.field1, t2.field2) as myfield
    

    coalesce() 在其参数中返回第一个非null 值。所以如果不是null,它会给你t1.field1,否则它会退回到t2.field2。如果两者都是null,则结果是null

    您也可以使用 case 表达式 - 与 colaesce() 相比没有任何好处,但这可以处理比无效检查更复杂的情况

    case
        when t1.field1 is not null then t1.field1
        when t2.field2 is not null then t2.field2
    end as myfield
    

    case 在满足条件的第一个分支上停止。如果没有分支匹配,则返回 null - 您可以在代码末尾添加 else 分支以返回其他内容。

    请注意,这两种技术都要求两个字段具有相似的数据类型。

    您没有显示您的实际查询,因此我无法说明如何在您的代码中使用它。

    【讨论】:

    • 专线小巴,谢谢!下面是我的实际查询: select view_episode_summary_current.patient_name_first, substring(view_episode_summary_current.patient_home_phone, 1, 3) || ' ' || substring(view_episode_summary_current.patient_home_phone, 5, 8), convert (varchar(10), CAST(appointment_date as date), 101) as "Date", CONVERT (time,appointment_start_time) as "Appointment State Time", Left(staff_name,charindex (',', staff_name)-1) 作为“SYSTEM”中的“员工姓氏”。“appt_data”,“SYSTEM”。“view_episode_summary_current” ...
    • 有什么建议吗?
    猜你喜欢
    • 2016-08-09
    • 2014-07-26
    • 2018-01-13
    • 2015-02-20
    • 2015-09-06
    • 2016-11-13
    • 1970-01-01
    • 2014-05-17
    • 2018-07-16
    相关资源
    最近更新 更多