MySQL总计,直到每年的特定日期

时间:2019-01-23 15:58:19

标签: php mysql laravel

我有一个customer_invoices表,其中包含字段invoiced_at作为日期&total_price,我需要从每年年初到现在的发票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,因为数组中的每一行应代表total_priceJanuary 23rd为止的那一年的总和。

2 个答案:

答案 0 :(得分:1)

尝试以下查询

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();

答案 1 :(得分:0)

将另一个放置在过滤器中,以使发票日期小于当前日期。

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'); }