如何使用 Raw SQl / Laravel - Eloquent ORM 进行累计计数

How to do a cumulative count using Raw SQl / Laravel - Eloquent ORM

这更像是一个 SQL 问题,而不是一个 Laravel 问题。

我想根据带有 created_at 字段的 User 模型完成类似以下的操作。 (table 数据库中的用户)

created_at user_id
2022-04-30 1
2022-05-02 2
2022-05-03 4
date created_users_to_this_date total_users_created_to_date
2022-04 1 1
2022-05 2 3

知道怎么做吗?

到目前为止我做了什么(使用Eloquent ORM):

User::query()
   ->selectRaw("COUNT(*) created_users_to_this_date, DATE_FORMAT(created_at, '%Y-%m') date")
   ->orderBy('date')
   ->groupBy('date')
   ->get();

等同于SQL请求

select COUNT(*) created_users_to_this_date, DATE_FORMAT(created_at, '%Y-%m') date from `users` where `users`.`deleted_at` is null group by `date` order by `date` asc

于是返回

date created_users_to_this_date
2022-04 1
2022-05 2

谢谢你的帮助

你的等值 sql 将是

SELECT DATE ,
  @running_number:=@running_number+created_users_to_this_date AS created_users_to_this_date
   FROM (SELECT 
  COUNT(*) AS created_users_to_this_date,
  DATE_FORMAT(created_at, '%Y-%m') DATE
FROM
  users 
where users.deleted_at is null 
GROUP BY `date` 
ORDER BY `date` ASC ) final
JOIN (SELECT @running_number:=0) rn

如果你的mysql版本支持window功能,你可以尝试使用SUMwindow功能做累计计数

DB::table(DB::raw('(select COUNT(*) created_users_to_this_date, DATE_FORMAT(created_at, \'%Y-%m\') date 
    from `users` 
    where `users`.`deleted_at` is null 
    group by `date`) t1'))
->select('created_users_to_this_date','date',DB::raw('SUM(created_users_to_this_date) OVER(ORDER BY date) total_users_created_to_date'))
->get();
User::query()
 ->select('
 DB::raw('COUNT(DATE_FORMAT(created_at, \'%Y-%m\') = DATE_FORMAT(now(), \'%Y-%m\')) as created_users_to_this_date'),
 DB::raw('COUNT(DATE_FORMAT(created_at, \'%Y-%m\') <= DATE_FORMAT(now(), \'%Y-%m\')) as total_users_created_to_date'),
 DB::raw('DATE_FORMAT(created_at, '%Y-%m') as date')
 ')->orderBy('date')->groupBy('date')->get();