我有一个查询来获取一年中各月份的所有收入总和,但我想从没有记录的月份中获取零,我可以从查询中执行此操作吗?
这是我现在的查询:
$monthRevenueData = \CompanySubscription::selectRaw('SUM(billed_amount) as revenue, MONTHNAME(payment_date) as Month')
->groupBy(\DB::raw("YEAR(payment_date)"),\DB::raw("MONTH(payment_date)"))
->orderBy(\DB::raw("MONTH(payment_date)"))->get();
输出:
Month revenue
January 2000
August 3000
october 1000
即使该月没有记录,我也希望剩余月份的结果为 0。
最佳答案
使用 CTE 来规避此问题。
with allmonths as (
select 'January' month,
union
select 'February' month
union
select ...
)
select * from yourtable y, allmonths x
where x.month = month(y.datefield);
或者你可以使用 -
select COALESCE(your_table.revenue,0), allmonths.month from (
select 'January' month,
union
select 'February' month
union
select ...
) as allmonths
LEFT JOIN your_table on month(your_table.datefield) = allmonths.month;
MySQL CTE - https://dev.mysql.com/doc/refman/8.0/en/with.html
关于mysql - 即使没有该月的记录,如何从查询中获取所有月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50733576/