Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL aggregation query for SUM, but only allow positive sums (otherwise 0)

I want to query an orders table and show the customer id and the total of all his orders, however the orders can have positive or negative totals.

select customer_id, SUM(order_total) from orders group by customer_id;

Now my question - how can I achieve the following in one sql query:

If the total sum is positive, I want to display it as is; if the total sum is negative, I just want to display 0 instead the actual amount.

What I am looking for is a function that can handle this, similar to the IFNULL function (IFNULL(SUM(order_total),0)), but instead of checking for null, it should check for a negative result.

Pseudo code:

IFNEGATIVE(SUM(order_total),0)

Is there a simple way in standard sql (or specifically in Mysql 5.5, would also be ok).

like image 416
Mathias Conradt Avatar asked Jul 05 '11 11:07

Mathias Conradt


People also ask

How do I get only positive values in SQL?

To compute the absolute value of a number, use the ABS() function. This function takes a number as an argument and returns its value without the minus sign if there is one. The returned value will always be non-negative – zero for argument 0, positive for any other argument.

How do you sum positive and negative values in SQL?

You can use sign to separate the values: select Sum( ( Sign( n ) + 1 ) / 2 * n ) as PositiveSum, Sum( -( Sign( n ) - 1 ) / 2 * n ) as NegativeSum from YourTableOData; Sign returns 1 , 0 or -1 depending on the sign of the input value.

How do I do an aggregate sum in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.

Can use aggregate functions like Sum and Count?

An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function ignores NULL values when it performs the calculation, except for the count function.


2 Answers

SELECT customer_id,
  CASE 
    WHEN SUM(order_total) < 0 THEN 0
    ELSE SUM(order_total)
  END
  FROM orders 
  GROUP BY customer_id;

Check your execution plan, but the 2 SUMs will probably be optimized to a single SUM under the hood.

like image 52
dee-see Avatar answered Sep 19 '22 23:09

dee-see


Try with:

select customer_id, GREATEST( SUM(order_total),0) from orders group by customer_id;
like image 32
Tudor Constantin Avatar answered Sep 18 '22 23:09

Tudor Constantin