Laravel 5.4查询生成器SUM()来自两个不同的表

时间:2017-08-08 02:44:51

标签: php mysql laravel

我在从两个表中获取某个字段的SUM时遇到问题。

所以要开始,这是我的查询。

        //Getting of Cost of Goods Sold (Menus)
        $totalMenuCost = DB::raw('(SUM(orders.qty * orders.cost)) as cost');
        $yearMenuSold = DB::raw('YEAR(orders.created_at) as year');

        $menuscost =  DB::table('orders')
            ->where('status', 'served')
            ->select($totalMenuCost, $yearMenuSold);

        //Getting of Cost of Goods Sold (Items)
        $totalItemCost = DB::raw('(SUM(purchases.qty * purchases.cost)) as cost');
        $yearItemSold = DB::raw('YEAR(purchases.created_at) as year');

        $itemcost =  DB::table('purchases')
            ->where('status', 'served')
            ->union($menuscost)
            ->select($totalItemCost, $yearItemSold)
            ->get();

当我尝试做return $itemcost时。它返回两行:

[
  {
    cost: "792.00",
    year: 2017
  },

  {
    cost: "1700.00",
    year: 2017
  }
]

我正在尝试让它返回一行但添加它,如下所示:

[
  {
    cost: "2492.00", // that's 1,700 + 792
    year: 2017
  }
]

2 个答案:

答案 0 :(得分:0)

$itemcost =  DB::table('purchases')
            ->where('status', 'served')
            ->union($menuscost)
            ->select($totalItemCost, $yearItemSold)
            ->get();

在你的例子中,你只是从其他表中选择$ totalItemCost,$ yearItemSold和union($ menuscost)。

这样就不会把结果加起来。

///////////尝试以此格式更改您的查询

select column1,sum(column2) total
from
(
    select column1,column2
    from Table1
    union all
    select column1,column2
    from Table2
) t
group by column1

希望这有助于...... 如果需要更多帮助,请告诉我。

答案 1 :(得分:0)

一切似乎都没问题,你有没有像这样改变$itemcost

$itemcost =  DB::table('purchases')
             ->where('status', 'served')
             ->select($totalItemCost, $yearItemSold)
             ->union($menuscost)
             ->groupBy('year')
             ->get();

<强>更新

由于以上不适用于您的情况,

我认为分组上的问题与联盟有关,所以请对此进行一次新尝试。

$menuscost =  DB::table('orders')
        ->where('status', 'served')
        ->select($totalMenuCost, $yearMenuSold)
        ->groupBy('year');

$itemcost =  DB::table('purchases')
             ->where('status', 'served')
             ->select($totalItemCost, $yearItemSold)
             ->groupBy('year')
             ->union($menuscost)
             ->groupBy('year')
             ->get();

如果这不起作用,那么可以添加此查询的输出。