如何在 SQL 中使用连续的条件从句?

How can I use consecutive conditional clause in SQL?

我试图在 Postgresql 中使用 CASE WHEN 来评估一些东西然后做另一件事。但是,我不仅需要检查两件事,而且必须按连续顺序检查它们。

例如,假设我有 3 列:col1、col2 和 col3。 我想先检查 col1 是否大于 0。检查完后我想检查 col2 是否大于 0。如果是这样,我将创建另一列,它将是所有列的总和。但是,我不能这样做:

select case when col1>0 and col2>0 then col1+col2+col3 end as...

我需要做这样的事情:

select case when col1>0 then (case when col2>0 then col1+col2+col3) else NULL end as...

但这不起作用。那么,我能做什么?

你很接近。你可以这样做:

select 
  case when col1 > 0 then case when col2 > 0 then col1 + col2 + col3 end
       else NULL end as my_column1

你错过了内幕end

顺便说一句,当没有 when 子句匹配时,CASE 表达式的计算结果为 NULL。因此,else NULL 是多余的。