在 Laravel 中获取按天排序的每日聚合/总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16764346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:49:38  来源:igfitidea点击:

Getting daily aggregates/sum sorted by day in Laravel

laravelaggregates

提问by Kylie

So getting a sum()/count() is really easy in Laravel... but how would I look at the past month, and get the sum of rows every day?

所以在 Laravel 中获得 sum()/count() 真的很容易......但是我将如何看待过去一个月,并每天获得行的总和?

EG...grouped by day that they were created at.

EG...按创建日期分组。

So I want to return a count such as 3, 2, 4, 5 Meaning 3 rows were created on todays date, 2 rows yesterday, 4 rows the day before...etc

所以我想返回一个计数,例如 3, 2, 4, 5 这意味着今天创建了 3 行,昨天创建了 2 行,前一天创建了 4 行......等等

How to do this in Laravel easily? When I use the group by created_at it always just returns 1.

如何在 Laravel 中轻松做到这一点?当我通过 created_at 使用组时,它总是只返回 1。

Anybody know how to do it?

有人知道怎么做吗?

Thanks

谢谢

回答by vFragosop

I've provided the same answer on another post. Shortening it:

在另一篇文章中提供了相同的答案。缩短它:

$date = new DateTime('tomorrow -1 month');

// lists() does not accept raw queries,
// so you have to specify the SELECT clause
$days = Object::select(array(
        DB::raw('DATE(`created_at`) as `date`'),
        DB::raw('COUNT(*) as `count`')
    ))
    ->where('created_at', '>', $date)
    ->group_by('date')
    ->order_by('date', 'DESC')
    ->lists('count', 'date');

// Notice lists returns an associative array with its second and
// optional param as the key, and the first param as the value
foreach ($days as $date => $count) {
    print($date . ' - ' . $count);
}