如果应用条件,则应执行查询

if condition is applied, then query should be excuted

我想对那些只有 (buy_rate - sell_rate) = 结果 > 0 的列进行 SUM。

换句话说,如果 buy_rate 大于 sell_rate,则 buy_rate - sell_rate = profit,将此计算应用于所有行并添加所有结果一起。

   DB::table('finaltrade')
   
      ->select(DB::raw("SUM(ABS(buy_rate - sell_rate)) AS total_profit"))
      ->get();

finaltrades table 结构:

id   user_id   exchange_id   market_id   symbol_id      buy_datetime          sell_datetime      buy_rate   sell_rate   quantities  
 ---- --------- ------------- ----------- ----------- --------------------- --------------------- ---------- ----------- ------------ 
   1         1             1           1          96   2018-05-25 18:13:26   0000-00-00 00:00:00       2205           0          100  
   2         1             1           1          96   0000-00-00 00:00:00   2018-05-25 18:13:59          0        6680          100  
   3         4             1           1          23   2018-05-25 18:16:27   0000-00-00 00:00:00          0           0           10  
   4         1             1           1          96   2018-05-25 18:13:59   0000-00-00 00:00:00      50351           0           30  
   5         1             1           1          15   0000-00-00 00:00:00   2018-05-25 18:34:46          0         100          150  
   6         4             1           1         573   2018-05-26 09:29:17   2018-05-27 03:10:09         10          10           10  
   7         1             1           1          15   2018-05-11 09:30:54   2018-05-25 18:34:56         40         100           40

在SQL中,我想你想要:

select sum(buy_rate - sell_rate) as profit
from finaltrade
where buy_rate > sell_rate;

如果您不需要 where 子句,则使用条件聚合:

select sum(case when buy_rate > sell_rate then buy_rate - sell_rate else 0 end) as profit
from finaltrade;

你可以这样做:

select sum((buy_rate > sell_rate)*(buy_rate - sell_rate)) as profit from finaltrade;