根据日期和名称汇总行

f45qwnt8  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(256)

我试图根据一个表中的项目名称对项目的数量求和,然后求项目的乘积。
我有两张table(酒吧和酒馆),如图所示。
1:钢筋

id |  name  |cost|
 1   item1   2000
 2   item2   5000

2:饮料销售

id | drink | no_drinks | date
1    item2     2         2018-08-01
2    item1     2         2018-08-01
3    item2     2         2018-08-01
4    item2     1         2018-08-01

我在这里的目的是根据假设为(5)的日期和假设为(2)的项目1求项目2的总成本,从那里我必须运行一个查询,从“bar”表中获取项目1和项目2的成本。我需要这样的结果
(55000)+ (22000) = 29000
这是我的剧本,关于连接的一切都没问题。
1:reportcontroler.php

$resx=DB::table('drinksales')
                ->join('bars','bars.name', '=' ,'drinksales.drink')
                ->where('date','LIKE','%'.$date.'%')
                ->get(array(
                    'bars.cost',
                    DB::raw('SUM(bars.cost) AS costs'),
                    DB::raw('SUM(drinksales.no_drinks) AS no_drinks')
                ));
            if($resx){
            foreach ($resx as $row) {
                $datas = array(
                    'amount' => $row->costs,
                    'no_drinks' => $row->no_drinks

                );
            }
                return View::make('reports.restaurantsreportcostd',$datas);
            }
            $datas=array(
                'amount'=>'No money collected'
            );
            return View::make('reports.restaurantsreportcostd',$datas);

在查询上述脚本后,我得到119000,这不是我想要的答案。
这里有一个视图文件
2:reports.restaurantsreportcostd

<p class="alert alert-success text-center">Total income {{$amount*$no_drinks}} /= </p>

有什么需要帮忙的吗?如果我解释得不好,很抱歉

c2e8gylq

c2e8gylq1#

它的计算是错误的,因为它所做的只是把所有的成本加起来,然后把所有的饮料加起来,再乘以。
我重述了你的逻辑来达到你想要的结果:

$resx = DB::table('drinksales')
    ->join('bars', 'bars.name', '=', 'drinksales.drink')
    ->where('date', 'LIKE', '%' . $date . '%')
    ->get();

$datas = array(
    'amount' => 0,
    'no_drinks' => 0,
    'total_income' => 0
);

if ($resx) {
    foreach ($resx as $row) {
        $datas['amount']+= $row->cost;
        $datas['no_drinks']+= $row->no_drinks;
        $datas['total_income']+= $row->cost * $row->no_drinks;
    }
} else {
    $datas['amount'] = 'No money collected';
}

return View::make('reports.restaurantsreportcostd', $datas);

你现在可以直接用我设置的附加变量得到总收入:

<p class="alert alert-success text-center">Total income {{ $total_income }} /= </p>
yzxexxkh

yzxexxkh2#

请使用groupby语句。 SELECT SUM(Drinnksales.no_drinks * COST) 在此处插入加入代码 GROUP BY Drinksales.Drink

相关问题