简体   繁体   中英

Group by month and order the dates on Laravel Eloquent

I have the following query

$months = \App\DATA::select(
    DB::raw('sum(order_value) as `sums`'),
    DB::raw("DATE_FORMAT(created_at,'%M %Y') as months")
)
    ->where("created_at", ">", \Carbon\Carbon::now()->subMonths(6))
    ->groupBy('months')
    ->get();

that makes a sum of the data for every month in the past 6 months. The problem is that it is outputting the dates in alphabetical order.

August 2019
July 2019
June 2019
May 2019
November 2019
October 2019
September 2019

I cannot order it with a orderBy :

->orderBy('created_at')

due to the following problem

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column

How can I order it by date?

Try with max function and ->orderBy('createdAt', 'desc') .

$months = \App\DATA::select(
       DB::raw('sum(order_value) as `sums`'),
       DB::raw("DATE_FORMAT(created_at,'%M %Y') as months"),
       DB::raw('max(created_at) as createdAt')
)
      ->where("created_at", ">", \Carbon\Carbon::now()->subMonths(6))
      ->orderBy('createdAt', 'desc')
      ->groupBy('months')
      ->get();

Just order your data by created_at :

$months = \App\DATA::select(
    DB::raw('ANY_VALUE(created_at) AS created_at')
    DB::raw('sum(order_value) as `sums`'),
    DB::raw("DATE_FORMAT(created_at,'%M %Y') as months")
)
    ->where("created_at", ">", \Carbon\Carbon::now()->subMonths(6))
    ->orderBy('created_at')
    ->groupBy('months')
    ->get();

you can use sort function to alphabetical order.

And

use GroupBy created_at

like

$months = \App\DATA::select(
       DB::raw('sum(order_value) as `sums`'),
       DB::raw("DATE_FORMAT(created_at,'%M %Y') as months"),
       DB::raw('max(created_at) as createdAt')
)
      ->where("created_at", ">", \Carbon\Carbon::now()->subMonths(6))
      ->orderBy('createdAt', 'desc')
      ->groupBy('months')
      ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM