用于避免检查空值评估的where子句中的case语句

时间:2014-11-10 10:14:50

标签: sql postgresql

我有像

这样的查询
case when (
  select sum(amount) 
  from table 
  where id in(10,100) 
    and to_char(month,'YYYY-MM') = to_char(@date::date,'YYYY-MM')
) is null 
then (
  select sum(amount) 
  from table 
  where id in(10,100) 
    and to_char(month,'YYYY-MM') = to_char(@date::date- interval '1 month','YYYY-MM')
)
else (
  select sum(amount) 
  from table 
  where id in(10,100) 
    and to_char(month,'YYYY-MM') = to_char(@date::date,'YYYY-MM')
) end

我只需要重写这个查询,我们可以在postgres的where子句中使用case语句

1 个答案:

答案 0 :(得分:0)

我认为你想要这样的东西,但不是很清楚。

coalesce(select sum(amount) 
      from table 
      where id in(10,100) 
        and to_char(month,'YYYY-MM') = to_char(@date::date,'YYYY-MM')
    ,
     select sum(amount) 
      from table 
      where id in(10,100) 
        and to_char(month,'YYYY-MM') = to_char(@date::date- interval '1 month','YYYY-MM')
    )