简体   繁体   English

PostgreSQL 中的案例

[英]CASE in PostgreSQL

I have a SELECT statement in T-SQL which replace null string to "N/A"我在 T-SQL 中有一个 SELECT 语句,它将 null 字符串替换为“N/A”

select 
  firstName,
  lastName,
  case city
    when null then 'N/A'
    else city
  end,
  case state
    when null then 'N/A'
    else state
  end 
from 
  Person left join Address on Person.personId = Address.personId

Output in T-SQL: T-SQL 中的 Output:

 ------------------------------ ------------------------------ ------------------------------ ------------------------------
 Allen                          Wang                           N/A                            N/A
 Bob                            Alice                          New York City                  New York

How do I do this in PostgreSQL?如何在 PostgreSQL 中执行此操作?

The problem is that you're comparing to NULL , and standard SQL semantics of comparisons of NULL don't work like this.问题是您要与NULL进行比较,而 NULL 比较的标准NULL语义不能这样工作。 A simple case uses = (equals) behaviour, and something = NULL is UNKNOWN , which inside a CASE behaves as FALSE .一个简单的案例使用= (equals) 行为,而something = NULLUNKNOWN ,在CASE中表现为FALSE

Solutions:解决方案:

  1. Use coalesce :使用coalesce

     coalesce(state, 'N/A'),
  2. Use a searched case instead of a simple case:使用搜索案例而不是简单案例:

     case when state is null then 'N/A' else state end

dbfiddle: https://dbfiddle.uk/GHWG38c5 dbfiddle: https://dbfiddle.uk/GHWG38c5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM