如何在sql中跳过case语句?

时间:2017-03-29 10:41:22

标签: sql postgresql select case

我在Postgresql中使用sql语句。在我的陈述中是一个案例表达。如果案例陈述不可接受,我怎么能跳过一行

代码:

SELECT *
FROM (SELECT a.link_id AS LinkID,

CASE
    WHEN a.From_Ref_Speed_Limit is null and a.To_Ref_Speed_Limit is not null THEN a.To_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit is not null and a.To_Ref_Speed_Limit is null THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit < a.To_Ref_Speed_Limit THEN a.To_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit > a.To_Ref_Speed_Limit THEN a.From_Ref_Speed_Limit
    WHEN a.From_Ref_Speed_Limit = a.To_Ref_Speed_Limit THEN a.To_Ref_Speed_Limit
    ELSE 0 --unknown
END as SpeedLimit,...

如果我的case语句中没有条件有罪,它应该跳过该行并选择下一行。 就像在其他情况下它不应该返回NULL它应该跳过该行,并应该继续下一个。 我怎么能意识到这一点?

1 个答案:

答案 0 :(得分:2)

您的case可以替换为greatest,而lateral可以避免嵌套查询:

select *
from
    a
    inner join lateral (
        select greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    ) s on s.SpeedLimit is not null
;
 from_ref_speed_limit | to_ref_speed_limit | speedlimit 
----------------------+--------------------+------------
                    1 |                  0 |          1
                    0 |                  1 |          1
                      |                  1 |          1
                    0 |                    |          0

对于9.4之前的版本(无横向),需要嵌套查询:

with a (From_Ref_Speed_Limit, To_Ref_Speed_Limit) as ( values
    (1,0),(0,1),(null,1),(0,null),(null,null)
)
select *
from (
    select a.*, greatest(a.From_Ref_Speed_Limit, a.To_Ref_Speed_Limit) as SpeedLimit
    from a
) s
where s.SpeedLimit is not null
;