doulao3905 2017-08-08 02:44
浏览 333

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

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. 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
  }
]
  • 写回答

2条回答 默认 最新

  • douqu2481 2017-08-08 03:43
    关注
    $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).

    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.

    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向