我有一個函數可以返回每天的銷售計數。這種方法的問題是,我希望將數據按日期存儲,但我讓他們按以下順序:按日期排序的退貨數據
01-Dec
02-Dec
03-Dec
03-Nov
04-Nov
05-Nov
etc.
我明白爲什麼出現這種情況,但我不知道如何解決它。我可以用startofmonth代替subMonth(1),這會部分解決我的問題,但這不是我想要的。我反而希望返回訂購的最後30天。
return DB::table('sales')
->select(\DB::RAW('DATE_FORMAT(created_at, "%d-%M") as date'), \DB::raw('COUNT(*) as count'))
->where('created_at', '>=', Carbon::now()->subMonth(1))
->orderBy('date')
->groupBy('date')
->get(['date', 'count'])
->keyBy('date')
->transform(function ($data) {
return $data->count;
});
我也試過orderBy('created_at'),但它給了我下面的錯誤,我想避免更改sql模式。
Syntax error or access violation: 1055 Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'x.sales.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
編輯: 按照要求,該return語句
select DATE_FORMAT(created_at, "%d-%M") as date, COUNT(*) as count from `sales` where `created_at` >= ? group by `date` order by `date` asc
請張貼生成的SQL – lad2025
@ lad2025我只是沒:) – George
請嘗試:' - > GROUPBY( '1')'代替' - > GROUPBY( '日')' – lad2025