为什么聚合函数在我的 laravel SQL 查询中不起作用?
Why does aggregation function does not work in my laravel SQL Query?
$year = date("y");
for($i=1;$i<=12;$i++)
{
$MonthlyReceive = DB::table('order_items') ->whereBetween('created_at',array($year.'-'.$i.'-1',$year.'-'.$i.'-31')) ->select(DB::raw('sum(price*quantity)'))->where('quantity','<','0');
return $MonthlyReceive;
}
// table name "order_items"
// id |product_id |quantity |price |order_id
您无需循环即可按月获取汇总数据。
$MonthlyReceive = DB::table('order_items')
->select(DB::raw('sum(price*quantity) as amnt'))
->whereRaw('date(created_at) between "'.$year.'-01-01" and "'.$year.'-12-31"')
->where('quantity','<','0')
->groupBy(DB::raw("date_format(created_at, '%Y-%M')"));
只需使用 group by
和聚合函数。
$year = date("y");
for($i=1; $i<=12; $i++) {
$MonthlyReceive = DB::table('order_items')
->whereBetween('created_at', array($year.'-'.$i.'-1',$year.'-'.$i.'-31'))
->where('quantity', '>', '0')
->sum(DB::raw('price*quantity'));
return $MonthlyReceive;
}
我已经用这段代码修复了它。
$year = date("y");
for($i=1;$i<=12;$i++)
{
$MonthlyReceive = DB::table('order_items') ->whereBetween('created_at',array($year.'-'.$i.'-1',$year.'-'.$i.'-31')) ->select(DB::raw('sum(price*quantity)'))->where('quantity','<','0');
return $MonthlyReceive;
}
// table name "order_items"
// id |product_id |quantity |price |order_id
您无需循环即可按月获取汇总数据。
$MonthlyReceive = DB::table('order_items')
->select(DB::raw('sum(price*quantity) as amnt'))
->whereRaw('date(created_at) between "'.$year.'-01-01" and "'.$year.'-12-31"')
->where('quantity','<','0')
->groupBy(DB::raw("date_format(created_at, '%Y-%M')"));
只需使用 group by
和聚合函数。
$year = date("y");
for($i=1; $i<=12; $i++) {
$MonthlyReceive = DB::table('order_items')
->whereBetween('created_at', array($year.'-'.$i.'-1',$year.'-'.$i.'-31'))
->where('quantity', '>', '0')
->sum(DB::raw('price*quantity'));
return $MonthlyReceive;
}
我已经用这段代码修复了它。