views:

169

answers:

4
ISNULL(SUM(MyTable.Total), 0) AS Total

how can i modify the above statement to also check if Total is less than 0 (zero), such that if Total is NULL or less than 0 (negative), i assign 0 to Total

+5  A: 
CASE 
WHEN COALESCE(SUM(MyTable.Total), 0) <= 0 THEN 0
ELSE SUM(MyTable.Total)
END AS [Total]
Ardman
A: 
CASE WHEN 
  COALESCE(SUM(MyTable.Total),0) <= 0 
THEN 
   0 
ELSE 
  SUM(MyTable.Total)
END AS Total
Paul Alan Taylor
Of course this does not do the SUM in the else case ... Tsk tsk tsk
Cobusve
+2  A: 
CASE WHEN ISNULL(SUM(MyTable.Total), 0) <= 0 THEN 0
     ELSE SUM(MyTable.Total)
END AS Total
lc
A: 

How about

SUM(ISNULL(MyTable.Total, 0)) AS Total

I prefer this as the NULL implementation in databases is not always logical and does differ between vendors and whether ANSI_NULLS are enabled or not.

E.g. SUM of NULL, NULL and 1 is returned as 1, but (1 + NULL + NULL) is equal to NULL ...

You can then do the less than 0 with the CASE as above, thus

CASE 
WHEN SUM(ISNULL(MyTable.Total,0)) <= 0 THEN 0
ELSE SUM(ISNULL(MyTable.Total,0))
END AS [Total]
Cobusve