【问题标题】:How to get the sum of columns from a group of records in a join?如何从连接中的一组记录中获取列的总和?
【发布时间】:2020-04-25 22:23:23
【问题描述】:

我有一个将文件退还给我的请求。我想把每个文件的货的总和汇总起来。

看起来像这样:

有文件。

  +-------------+----------+
  | document_id | owner_id | 
  +-------------+----------+
  | 52f20e4d    | ef27737d |  
  | 3bfdc5aa    | ef27737d |   
  +-------------+----------+

产品附在每个文件上。

  +-------------+-------------+-----------+
  | product_id  | document_id | total_sum |
  +-------------+-------------+-----------+
  | b60624a7    | 52f20e4d    | 10        |
  | fcc21801    | 52f20e4d    | 5         |
  | d5cbe99d    | 3bfdc5aa    | 3         |
  | 5e537533    | 3bfdc5aa    | 4         |
  +-------------+-------------+-----------+

我的php代码:

$result = DB::table('documents as docs')->leftJoin('products as t_products', function($join) {
    $join->on('t_products.document_id', '=', 'docs.document_id');
})->where('docs.owner_id', '=', $currentUserId)->select('docs.document_id', 't_products.total_sum')
    ->get();

return response()->json($result);

我得到以下信息:

[
  {
      "document_id": "52f20e4d",
      "total_sum": "5"
  },

  {
      "document_id": "52f20e4d",
      "total_sum": "10"
  },

  {
      "document_id": "3bfdc5aa",
      "total_sum": "4"
  },

  {
      "document_id": "3bfdc5aa",
      "total_sum": "3"
  }
]

但我希望只看到两个将汇总 total_sum 的条目。

像这样:

[
    {
        "document_id": "52f20e4d",
        "total_sum": "15"
    },

    {
        "document_id": "3bfdc5aa",
        "total_sum": "7"
    }
]

【问题讨论】:

    标签: laravel postgresql laravel-query-builder


    【解决方案1】:

    按文档ID和总和添加分组

    $result = DB::table('documents as docs')
        ->leftJoin('products as t_products', function($join) {
            $join->on('t_products.document_id', '=', 'docs.document_id');
        })
        ->where('docs.owner_id', '=', $currentUserId)
        ->selectRaw('docs.document_id, sum(t_products.total_sum) as total_sum')
        ->groupBy('docs.document_id')
        ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 2012-02-09
      相关资源
      最近更新 更多