【问题标题】:Laravel querying to get the sum of a column for each monthLaravel查询以获取每个月的列总和
【发布时间】:2019-04-05 19:45:02
【问题描述】:

我正在使用查询来计算每个月的列的总和,问题是当我获取数据并且一个月没有数据时,该月没有行,然后我不知道哪个是哪个月份,如果月份金额为 0,则返回 0 会很有帮助, 这是查询:

$test = DB::table('actuals')
->Where('company_id',$id)
->Where('account_level_l','LIKE','%Income%')
->select(DB::raw('SUM(amount) as total_amount'))
->groupBy(DB::raw('MONTH(date) ASC'))->get();

这是返回的对象,从 12 个月开始有 10 个数据:

Collection {#1381 ▼
  #items: array:10 [▼
    0 => {#1370 ▼
      +"total_amount": 133409.46
    }
    1 => {#1371 ▼
      +"total_amount": 77421.36
    }
    2 => {#1372 ▼
      +"total_amount": 78193.81
    }
    3 => {#1373 ▼
      +"total_amount": 940477.66
    }
    4 => {#1374 ▼
      +"total_amount": 81713.1
    }
    5 => {#1375 ▼
      +"total_amount": 64792.43
    }
    6 => {#1376 ▼
      +"total_amount": 85099.41
    }
    7 => {#1377 ▼
      +"total_amount": 127753.07
    }
    8 => {#1378 ▼
      +"total_amount": 62953.11
    }
    9 => {#1379 ▼
      +"total_amount": 356.61
    }
  ]
}

【问题讨论】:

  • 为什么你不在查询中选择月份名称或月份编号,结果为总金额和月份
  • @Thamerbelfkih 你能帮我吗
  • 请检查我的回复

标签: php laravel-5


【解决方案1】:

您只需在查询中选择月份编号,如下所示:

$test = DB::table('actuals')
->Where('company_id',$id)
->Where('account_level_l','LIKE','%Income%')
->select(DB::raw('SUM(amount) as total_amount, MONTH( date ) as month'))
->groupBy(DB::raw('MONTH(date) ASC'))->get();

这将给出每一行的number of monthtotal_amount

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多