2017-12-03 166 views
1

我有一個函數可以返回每天的銷售計數。這種方法的問題是,我希望將數據按日期存儲,但我讓他們按以下順序:按日期排序的退貨數據

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 
+0

請張貼生成的SQL – lad2025

+0

@ lad2025我只是沒:) – George

+0

請嘗試:' - > GROUPBY( '1')'代替' - > GROUPBY( '日')' – lad2025

回答

0

的SQL查詢我沒有你的框架查詢語法太多的想法。但是您可以在顯示數據時再添加一列DATE_FORMAT(created_at,「%Y%m%d」)作爲order_column並應用順序,並按列「order_column」分組,並使用列「data」。

select DATE_FORMAT(created_at, "%Y%m%d") AS order_column, DATE_FORMAT(created_at, "%d-%M") as date, COUNT(*) as count from `sales` where `created_at` >= ? group by `order_column` order by `order_column` asc 



return DB::table('sales') 
     ->select(\DB::RAW('DATE_FORMAT(created_at, "%Y%m%d") AS order_column'),\DB::RAW('DATE_FORMAT(created_at, "%d-%M") as date'), \DB::raw('COUNT(*) as count')) 
     ->where('created_at', '>=', Carbon::now()->subMonth(1)) 
     ->orderBy('order_column') 
     ->groupBy('order_column') 
     ->get(['date', 'count']) 
     ->keyBy('date') 
     ->transform(function ($data) { 
      return $data->count; 
     }); 
+0

Yeap,這與獲取原始'created_at'值相同。我可以按原始的created_at排序,但是我得到了上面提到的錯誤(sql_mode = only_full_group_by)和兩種情況。我想我將不得不改變mysql設置來完成這個... – George

0

如果你在2個步驟中做到這一點,它是否工作?

第一步,在其中創建日期列:

$step1 = DB::table('sales') ->select(\DB::RAW('DATE_FORMAT(created_at, "%d-%M") as date'))) 
->where('created_at', '>=', Carbon::now()->subMonth(1)) 
->orderBy('date') 
->get(['date', 'count']) 

之後,你做agregation:

$step2 = $step1->select('date'), \DB::raw('COUNT(date) as count')) 
->groupBy('date') ->get(['date', 'count']) ->keyBy('date') 

希望它能幫助!