[英]MySQL SUM up until a specific date for each year
我有一个customer_invoices
包含的字段表invoiced_at
的日期和total_price
,我需要的SUM total_price
从每年直到同一天,今天,通过一年分组开始时的发票,并从一个特定的一年,我提供启动.
到目前为止我所做的:
public function totalIncomeToCurrentDayByYear($startingAt)
{
return CustomerInvoice::selectRaw('sum(total_price) as total')
->where('customer_invoices.status', Status::VALIDATED)
->selectRaw("DATE_FORMAT(invoiced_at,'%Y') as year")
->whereRaw("DATE_FORMAT(invoiced_at,'%Y') >= $startingAt")
->groupBy('year')
->get()
->pluck('total', 'year');
}
我需要得到与此类似的结果:(在这种情况下,我得到了全年的总和,这不是我想要的):
totalIncomeToCurrentDayByYear(2003); // ==>
#items: array:14 [▼
2003 => "144.52"
2006 => "11455.00"
2007 => "27485.40"
2008 => "39268.08"
2009 => "37434.19"
2010 => "443631.75"
2011 => "2275159.26"
2012 => "3874576.94"
2013 => "4994901.19"
2014 => "5968874.72"
2015 => "7250182.95"
2016 => "9017509.81"
2017 => "10704557.00"
2018 => "12637778.13"
]
例如,今天是January 23rd
,数组中的每一行都应该代表那一年直到January 23rd
的total_price
。
试试下面的查询
CustomerInvoice::whereRaw("DATE_FORMAT(invoiced_at,'%Y') >= $startingAt")
->where('customer_invoices.status', Status::VALIDATED)
->whereRaw('MONTH(invoiced_at) < MONTH(NOW()) or
(MONTH(invoiced_at) = MONTH(NOW()) and DAY(invoiced_at) <=
DAT(NOW()))')
->select(DB::raw('YEAR(invoiced_at) invoiced_year' ),
DB::raw('SUM(total_price) total_price'))-
>groupBY(DB::raw('YEAR(invoiced_at)')
->orderBy(DB::raw('YEAR(invoiced_at)')->get();
放置另一个 where 过滤器,使发票日期小于当前日期。
public function totalIncomeToCurrentDayByYear($startingAt,$currentDate) { return CustomerInvoice::selectRaw('sum(total_price) as total') ->where('customer_invoices.status', Status::VALIDATED) ->selectRaw("DATE_FORMAT(invoiced_at,'%Y') as year") ->whereRaw("DATE_FORMAT(invoiced_at,'%Y') >= $startingAt")->whereRaw("invoiced_at <= $currentDate") ->groupBy('year') ->get() ->pluck('total', 'year'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.