[英]Laravel 5.4 Query Builder SUM() from two different tables
I'm having problems getting the SUM of a certain field from two tables. 我在从两个表中获取某个字段的总和时遇到问题。
So to start things off, here's my query. 因此,从这里开始,这是我的查询。
//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();
And when I try to do return $itemcost
. 当我尝试
return $itemcost
。 It returns two rows: 它返回两行:
[
{
cost: "792.00",
year: 2017
},
{
cost: "1700.00",
year: 2017
}
]
I'm trying to make it return a single row but having it added, like this: 我试图使它返回一行,但添加了它,如下所示:
[
{
cost: "2492.00", // that's 1,700 + 792
year: 2017
}
]
$itemcost = DB::table('purchases')
->where('status', 'served')
->union($menuscost)
->select($totalItemCost, $yearItemSold)
->get();
In your Example you are just selecting $totalItemCost, $yearItemSold and union from other table ($menuscost). 在您的示例中,您只是从其他表中选择$ totalItemCost,$ yearItemSold和并集($ menuscost)。
So that won't add up the results. 这样就不会加总结果。
///////////Try Changing your Query in this Format ////////////尝试以这种格式更改查询
select column1,sum(column2) total
from
(
select column1,column2
from Table1
union all
select column1,column2
from Table2
) t
group by column1
Hope this Helps.. Let me know if more help is needed. 希望对您有帮助。请让我知道是否需要更多帮助。
All seems okay, Have you changed your $itemcost
like this 一切似乎还好,您是否更改了
$itemcost
这样的
$itemcost = DB::table('purchases')
->where('status', 'served')
->select($totalItemCost, $yearItemSold)
->union($menuscost)
->groupBy('year')
->get();
UPDATE UPDATE
Since above not working for your case, 由于上述情况不适用于您的情况,
I think problem on group by is with union so Have a new try with this one. 我认为分组的问题是与工会有关,因此对此有新的尝试。
$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();
If this is not working then can you add output of this query. 如果这不起作用,那么您可以添加此查询的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.