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).
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.
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.
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.
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.
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 SUM
s will probably be optimized to a single SUM
under the hood.
Try with:
select customer_id, GREATEST( SUM(order_total),0) from orders group by customer_id;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With