Link to home
Start Free TrialLog in
Avatar of Gray5452
Gray5452

asked on

SQL Syntax IIF in select to prevent Divide by Zero

getting this error

Msg 102, Level 15, State 1, Line 7
Incorrect syntax near '>'.

when using this syntax


      SELECT sitename,
               campaign,
               SUM(cost)as sitecost,
               SUM(calls)as sitecalls,
               
               IIF(sum(calls)>0,(SUM(cost)/SUM(calls)),0) as 'CPC'
               
      FROM [KoolSmiles].[dbo].[v_DigitalMedia]
      where (REportDate between '3/14/11' and '3/20/11')and sitename = 'Google'--where (REportDate between @start and @end)and sitename = 'Google'
      group by sitename,campaign
Avatar of chapmandew
chapmandew
Flag of United States of America image

case when sum(calls)>0 then (SUM(cost)/SUM(calls)),0) else 0 end as 'CPC'
ASKER CERTIFIED SOLUTION
Avatar of Roman Gherman
Roman Gherman
Flag of Moldova, Republic of image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if you don't want NULL as cpc, you can try ISNULL.
SELECT sitename,
               campaign,
               SUM(cost)as sitecost,
               SUM(calls)as sitecalls,
               
               isnull(SUM(cost)/NULLIF(SUM(calls),0),0) as 'CPC'
               
      FROM [KoolSmiles].[dbo].[v_DigitalMedia]
      where (REportDate between '3/14/11' and '3/20/11')
        and sitename = 'Google'
      group by sitename,campaign

Open in new window

Avatar of Gray5452
Gray5452

ASKER

both worked perfectly,,I'd be lost without this site..

Thanks Again..