简体   繁体   English

SQL 对 SUM 的聚合查询,但只允许正和(否则为 0)

[英]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.我想查询一个订单表并显示客户 ID 和他所有订单的总数,但是订单总数可以是正数或负数。

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:现在我的问题 - 如何在一个 sql 查询中实现以下目标:

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.如果总和为负,我只想显示 0 而不是实际金额。

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.我正在寻找的是可以处理此问题的 function ,类似于IFNULL function ( IFNULL(SUM(order_total),0) ),但不是检查 Z37A62596648DFFE299A ,而是检查结果是否为负。

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).在标准 sql 中是否有一种简单的方法(或者特别是在 Mysql 5.5 中,也可以)。

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.检查您的执行计划,但 2 SUM可能会优化为引擎盖下的单个SUM

Try with:尝试:

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

Not tested, but something like this should do it:未经测试,但应该这样做:

SELECT customer_id , IF( SUM(order_total) > 0, SUM(order_total), 0) AS sum FROM orders GROUP BY customer_id

if i understand its only wrap it with GREATEST如果我理解它只用GREATEST包裹它

SELECT customer_id, GREATEST(0,SUM(order_total)) 
FROM orders GROUP BY customer_id;

look on the link链接

Could you not use a CASE statement?你能不使用 CASE 语句吗?

Something like:就像是:

CASE WHEN [Field] < 0 THEN 0

Or did I miss something?还是我错过了什么?

select Id,case when (sum(amount)<0) then 0 else sum(amount) end  from tblsum group by Id

You can also try;你也可以试试;

select 
  (sum(fld) + abs(sum(fld))) / 2
from tbl

To only display positive Use HAVING thus:仅显示正面使用 HAVING :

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

Otherwise use case as listed elsewhere here否则这里其他地方列出的用例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM