返回按日期排序的数据

时间:2017-12-03 08:59:09

标签: php mysql sql laravel laravel-5

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

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

2 个答案:

答案 0 :(得分:0)

我对您的框架查询语法不太了解。但是您可以再添一个列DATE_FORMAT(created_at,"%Y%m%d")AS order_column并应用顺序,并按列分组#34; order_column"并使用列"数据"同时显示数据。

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;
        });

答案 1 :(得分: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']) 

然后你进行了聚会:

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

希望它有所帮助!