SOQL:避免使用NULL结果计数返回0(零)

时间:2014-03-28 12:17:22

标签: mysql sql salesforce soql

我有一个问题,我写了一个查询,我需要按给定的顺序返回机会的数量:Name1,Name2,Name3,Name4。问题是,如果计数为NULL,例如对于Name2,则查询返回Name1_count,Name3_count,Name4_count。

我需要确保我总是以正确的顺序获取值,如果值为null,我需要返回0.但它不起作用:(

我试过了:

Select Owner.Name
      ,IF(ISBLANK(count(id))
      ,0
      ,count(id)) 

  from Opportunity 

  where CloseDate = Today 
    and Approved__c = true 
    and (Owner.Name = 'Name1' 
         or Owner.Name = 'Name2' 
         or Owner.Name = 'Name3' 
         or Owner.Name = 'Name4') 

  group by Owner.Name 

1 个答案:

答案 0 :(得分:0)

您的查询使用名为owner的表别名,该别名未定义。据推测,这应该是指Opportunity,尽管这只是猜测。另外,要获得0 NULL,典型函数为coalesce()。我用or替换了一组复杂的in

Select o.Name, coalesce(count(id), 0) 
from Opportunity o
where CloseDate = Today and Approved__c = true and
      o.Name in ('Name1', 'Name2', 'Name3', 'Name4')
group by o.Name ;

最后,要在输出中获取所有四个名称,您需要使用left outer join

Select names.Name, count(o.id) as cnt
from (select 'Name1' as name union all select 'Name2' union all
      select 'Name3' union all select 'Name4'
     ) names left outer join
     Opportunity o
     on names.name = o.name
where CloseDate = Today and Approved__c = true
group by names.Name ;