繁体   English   中英

返回按日期排序的数据

[英]Return data ordered by date

我有一个函数可以返回每天的销售数量。 这种方法的问题是我希望按日期存储数据,但是我按以下顺序获取它们:

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

编辑:根据要求,这是返回语句的SQL查询

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

我对您的框架查询语法不太了解。 但是您可以再使用一列DATE_FORMAT(created_at,“%Y%m%d”)AS 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;
        });

如果分两个步骤进行,是否有效?

在其中创建日期列的Step1:

$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']) 

然后进行聚合:

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

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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