将条件和结果保存在变量MySQL中

时间:2017-03-28 12:33:21

标签: mysql performance sum

我被困在一个查询中我想将sum结果存储在status = 3的变量中,现在发生的事情是存储最后一行的值并用所有行显示

这是查询

    SELECT 
request_made_on,driver_id,
@sum_result = SUM(status = 3) AS complete_count,@sum_result,
SUM(status = 6) AS missed_count,
(status = 4) AS canceled_count,
sum(actual_fare),sum(discount)
 from tb_engagements
 group by date(request_made_on),driver_id;

and here is the screenshot, second screenshot

1 个答案:

答案 0 :(得分:0)

我猜你想要所有值的 sum

select request_made_on, driver_id,
       (@sum_result := @sum_result + SUM(status = 3)) AS complete_count,
       sum(status = 6) AS missed_count,
       sum(status = 4) AS canceled_count,
       sum(actual_fare),
       sum(discount)
from tb_engagements c cross join
     (select @sum_result := 0) params
group by date(accept_time), driver_id;

注意:

  • 您不需要返回变量的值以及表达式。该表达式使用值为结果集添加一列。
  • 您不需要if()来计算值。 MySQL有一个很好的简写,在数字上下文中将布尔表达式视为整数。