使用'案例'和select语句中的空时间戳

时间:2014-07-31 07:05:26

标签: sql postgresql case case-when

我在postgresql中使用case when块来确定结果的显示方式。该块如下:

(case 
    when four.status = 'active' and (four.expiration > (current_date + integer '{{expire_window}}')) then 'Active'
    when four.status = 'active' and (four.expiration is null) then 'Active'
    when four.status = 'pending' then 'Pending'
    when four.status = 'active' and (four.expiration <= (current_date + integer '{{expire_window}}')) then 'Expiring'

        else 'Missing' end) as certificate

expiration是时区数据类型的时间戳,如果没有任何内容,则为null。当到期为空时,我希望four.status显示为活动状态。我已添加该行when four.status = 'active' and (four.expiration is null) then 'Active',但由于某种原因,结果仍显示为Missing。如果我只使用when four.expiration is null then 'Active',则任何具有空过期DO的结果都会显示为“活动”。

如何检查同一four.status = 'Active'行中的four.expiration is nullwhen以获得正确的结果?

2 个答案:

答案 0 :(得分:0)

检查这是否适合你......

(case 
when (four.status = 'active' 
        and ((four.expiration is null)                   
             or (four.expiration > (current_date + integer '{{expire_window}}'))
            )) then 'Active'
when four.status = 'pending' then 'Pending'
when four.status = 'active' and (four.expiration <= (current_date + integer '{{expire_window}}')) then 'Expiring'

    else 'Missing' end) as certificate

答案 1 :(得分:0)

我无法重现它

with four(status, expiration) as ( values
    ('active'::text, '2014-12-31'::timestamp),
    ('active', null),
    ('pending', null),
    ('active', '2014-08-15')
)
select
case
    when status = 'active' and (expiration > (current_date + 30)) then 'Active'
    when status = 'active' and (expiration is null) then 'Active'
    when status = 'pending' then 'Pending'
    when status = 'active' and (expiration <= (current_date + 30)) then 'Expiring'
    else 'Missing'
end as certificate
from four
;
 certificate 
-------------
 Active
 Active
 Pending
 Expiring

这有点清洁

case status
    when 'active' then
        case
            when
                expiration is null or
                expiration > current_date + 30
                then 'Active'
            else 'Expiring'
        end
    when 'pending' then 'Pending'
    else 'Missing'
end as certificate