laravel MYSQL中带条件的减法运算

zkure5ic  于 2023-01-18  发布在  Mysql
关注(0)|答案(1)|浏览(187)

我想在mysql查询中的特定条件下进行求和和减法运算
我已经试过了,假设$balance = 655.000.000,那么my_table内的总金额= 80.000.000印尼盾和500.000美元

$currency_id = 1;
$balance = 655.000.000;
DB::table('my_table as a')
    ->join('master_currencies as b', 'a.master_currency_id', 'b.id')
    ->where('a.id', $id)
    ->selectRaw("SUM(
         CASE
             WHEN $currency_id = a.master_currency_id THEN $balance - a.amount
         ELSE
             a.amount
         END) AS net_value, b.symbol, b.id as master_currency_id"
         )
         ->groupBy('b.id')
         ->get();

上面的代码应该给予结果

[
  {"net_value":"575.000.000","symbol":"IDR","master_currency_id":1},
  {"net_value":"500.000","symbol":"USD","master_currency_id":2}
]

但我得到的结果是

[
  {"net_value":"1.885.000.000","symbol":"IDR","master_currency_id":1},
  {"net_value":"500.000","symbol":"USD","master_currency_id":2}
]

**注意:**请忽略数字之间的点,在我的数据库中我不使用这些点。它仅用于查询目的

ddrv8njm

ddrv8njm1#

如果您有多行IDR,那么可能是操作顺序的问题。
比如说你必须(十万元)及(50.000.000),则为印尼盾总和(655.000.000-100.000.000,655.000.000-50.000.000)=1.160.000.000,与655.000.000-总和不同(100.000.000,50.000.000)=505.000.000,问题是聚合的组中的每一行都得到一个干净的$balance
您可以通过执行以下操作来解决此问题:

$currency_id = 1;
$balance = 655.000.000;
DB::table('my_table as a')
    ->join('master_currencies as b', 'a.master_currency_id', 'b.id')
    ->where('a.id', $id)
    ->selectRaw("
         (CASE 
            WHEN a.id=$currency_id $balance-SUM(a.amount)
         ELSE
            SUM(a.amount)  
         END) AS net_value, b.symbol, b.id as master_currency_id")
         ->groupBy('b.id')
         ->get();

相关问题