• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 299
  • Last Modified:

group by error in divide by zero problem

Hi, below is my code along with the error message which
i am getting..i basically want to divide sum(total_spend)
by count(orders)..

  can any one please re-write my code in tsql so that
it does not return any error including divide by zero..

Many Thanks
select  case when orders = 0 then 0 else ISNULL(sum(total_spend)/count(orders),0) end as [count]
		from tmp_fov
		group by custid

error - Msg 8120, Level 16, State 1, Line 1
Column 'tmp_fov.orders' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Open in new window

0
gvamsimba
Asked:
gvamsimba
2 Solutions
 
chapmandewCommented:
select  case when count(orders) = 0 then 0 else ISNULL(sum(total_spend)/count(orders),0) end as [count]
                from tmp_fov
                group by custid
0
 
Aneesh RetnakaranDatabase AdministratorCommented:

select ISNULL(sum(CASE WHEN orders >0 THEN total_spend ELSE 0 END )/count(orders),0) as [count]
from tmp_fov
group by custid
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now