我从事务表中获取order_id,created_at date,transaction_amount。我使用order_id,其created_at日期和transaction_amount获得了一些记录。现在我想要transaction_amount列的总和。我尝试在db上直接查询哪个工作正常,但我无法在laravel中编写相同的查询。
select sum(transaction_amount) from (
select order_id, max(created_at), transaction_amount
from transactions
WHERE user_id =100 AND accounting_type = "Debit"
group by order_id
limit 500 ) as transactions
我试过这种方式但仍然无法正常工作
$sql = "select sum(transaction_amount) from
('select order_id, max(created_at), transaction_amount
from transactions
WHERE user_id =100
group by order_id
limit 500') as transactions";
$result = \DB::select( \DB::raw($sql));
答案 0 :(得分:3)
首先,让我们分解您的查询: 主要查询
SELECT
SUM( transaction_amount )
FROM
(...) AS transactions
这只是用于总结。你的子查询:
SELECT
order_id,
MAX( created_at ),
transaction_amount
FROM
transactions
WHERE
user_id = 100
AND accounting_type = "Debit"
GROUP BY
order_id LIMIT 500
对于子查询,Laravel查询构建器应为:
use DB;
$result = DB::table('table')
->select(DB::raw("order_id, MAX(created_at), transaction_amount"))
->where("user_id", "=", 100)
->where("accounting_type", "=", "Debit")
->groupBy("order_id")
->limit(500)
->get(); // this will return Laravel Collection (Illuminate\Support\Collection)
Laravel Collection有sum
方法,所以你可以调用它
$result->sum('transaction_amount');
答案 1 :(得分:0)
我认为您的$sql
变量必须只包含FROM
中的子查询。
Laravel QueryBuilder的table()
方法是" 等效"在SQL中FROM
语句中,您可以放置子查询。
尝试
$sql = 'select order_id, max(created_at), transaction_amount
from transactions
WHERE user_id =100
group by order_id
limit 500';
$result = \DB::table(\DB::raw($sql))->sum('transaction_amount');
相反,如果您想要与您尝试使用的select()
方法并行:
$result = \DB::table(\DB::raw($sql))->select(\DB::raw('sum(transaction_amount) as sum'))->get();