按日期排序的退货数据

我有一个函数可以返回每天的销售计数。这种方法的问题是,我希望将数据按日期存储,但我让他们按以下顺序:按日期排序的退货数据

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查询我没有你的框架查询语法太多的想法。但是您可以在显示数据时再添加一列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;

});

回答:

如果你在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')

希望它能帮助!

以上是 按日期排序的退货数据 的全部内容, 来源链接: utcz.com/qa/260143.html

回到顶部