Laravel查询两列之和之差

Posted

技术标签:

【中文标题】Laravel查询两列之和之差【英文标题】:Laravel query with difference of sum of two columns 【发布时间】:2021-09-26 19:57:08 【问题描述】:

我有一个似乎有一些问题的 Laravel 查询。它正在拾取所有正确的东西,但不计算两个字段之和的差。

JournalLine::join('accounts','accounts.id','account_id')
->select('accounts.name','accounts.code','accounts.id','accounts.type')
->whereHas('account_fk',function ($query) 
    $query->where('type','Liability');
)
->whereHas('journal_fk',function ($query) 
    $query->where('date', '<=', $this->as_of_date);
)
->selectRaw("SUM(credit) as credit")
->selectRaw("SUM(debit) as debit")
->selectRaw("SUM(credit) - SUM(debit) as amount")
->groupBy('account_id')
->get()->toArray()

它使贷方和借方值正确。但是平衡是错误的。 这有问题 - selectRaw("SUM(credit) - SUM(debit) as amount") 有人可以建议吗?我需要借方总和和贷方总和的余额。

【问题讨论】:

【参考方案1】:

有 2 个选择语句可能是你必须做的 1 像这样

JournalLine::join('accounts','accounts.id','account_id')
->selectRaw('accounts.name , accounts.code,accounts.id,accounts.type,SUM(accounts.credit) - SUM(accounts.debit) as amount')
->whereHas('account_fk',function ($query) 
    $query->where('type','Liability');
)
->whereHas('journal_fk',function ($query) 
    $query->where('date', '<=', $this->as_of_date);
)
->groupBy('account_id')
->get();

【讨论】:

这不起作用。我的查询实际上有三个语句。前两个工作正常,带来了聚合。第三个没用。 ->selectRaw("SUM(credit) as credit") ->selectRaw("SUM(debit) as debit") ->selectRaw("SUM(credit) - SUM(debit) as amount") 你试过这个代码吗?你得到了什么错误? 我稍微修改为 ->selectRaw('accounts.name,accounts.code,accounts.id,accounts.type,SUM(accounts.credit) as credit,SUM(accounts.debit) as debit,SUM(accounts.credit) - SUM(accounts.debit) as amount') 并给出以下结果 - prnt.sc/1cz53qy。如果 Debit 为 null,则抛出 null 并且不将 null/no 值视为 0【参考方案2】:

你可以使用它:

JournalLine::join('accounts','accounts.id','account_id') 
->select([
'accounts.name',
'accounts.code',
'accounts.id',
'accounts.type',
"SUM(credit) as credit",
"SUM(debit) as debit",
"(credit - debit) as amount"
])
->whereHas('account_fk',function ($query) 
    $query->where('type','Liability');
)
->whereHas('journal_fk',function ($query) 
    $query->where('date', '<=', $this->as_of_date);
)
->groupBy('account_id')
->get()->toArray()

【讨论】:

【参考方案3】:

一张表中两列的差值之和

$saleEarning     = Order::where("type","sale")->sum(DB::raw('totalAmt - adminCommision'));


Hope it help you.

【讨论】:

以上是关于Laravel查询两列之和之差的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 查询 col1 != col2

Laravel RAW 查询添加多列浮点值

Laravel - 加入然后别名两列

想比较laravel中不同表的两列

Laravel 关系一到两列

Laravel,两列之间的日期范围过滤器