每月计算客户数量无法起诉 Laravel 查询生成器

Count customers monthly is not working suing Laravel query builder

我的 SQL 查询工作正常。 在 SQL

中每月计算客户数
SELECT YEAR(created_at) AS Year, MONTH(created_at) AS Month, COUNT(customer_id) as Customers FROM customers GROUP BY Year, Month

与此等效的查询生成器。

$customers_permonth = DB::table('customers')->select('YEAR(created_at) as Year','MONTH(created_at) as Month')->groupBy('Year','Month')->count();

错误是: SQLSTATE[42S22]:未找到列:1054 'group statement' 中的未知列 'Year'(SQL:select 计数(*)来自 customersYearMonth)"

分组

您必须在分组依据中使用 created_at。尝试以下操作:

$customers_permonth = DB::table('customers')->select(DB::raw('YEAR(created_at) as Year, MONTH(created_at) as Month, count(*) as count')->groupBy(DB::raw('YEAR(created_at), MONTH(created_at)')->->get();

此查询将为您获取所有月度客户

$customers_permonth = DB::table('customers')::selectRaw('COUNT(*) as count, YEAR(created_at) year, MONTH(created_at) month')
->groupBy('year', 'month')
->get();