【问题标题】:Laravel Group By and Sum per grouped rowsLaravel Group By 和 Sum 每个分组的行
【发布时间】:2019-04-11 06:31:14
【问题描述】:

我的目标

我希望按订单的“type_id”对订单进行分组,并计算每组订单的“volume_remain”总和。我正在寻找一个查询来做到这一点。也许值得一提的是,我的订单表包含大约 200.000 行。

我使用 Laravel 框架 (5.8),我对非基本性质的查询缺乏经验。由于我缺乏经验,我没有尝试太多。

这就是我的订单表的构建方式。

Schema::create('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('type_id')->index();
            $table->bigInteger('order_id')->index();
            $table->integer('duration');
            $table->string('is_buy_order');
            $table->string('issued');
            $table->integer('location_id');
            $table->integer('min_volume');
            $table->bigInteger('price');
            $table->string('range');
            $table->integer('system_id');
            $table->integer('volume_remain');
            $table->integer('volume_total');
            $table->timestamps();
        });

type_id:表示游戏中的物品

订单:表示游戏市场上特定商品的 1 个订单

volume_remain:该特定订单的仍在市场上的商品数量

所以每个订单都属于一个type_id,一个type_id可以有很多个订单。

期望的结果

我想要的结果是按其 type_id 分组的订单集合,但仅限于不超过其 volume_remain 的特定总和的订单。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    你可以这样查询

    DB::table("orders")->select("id", "type_id", "order_id", "duration",  
    "is_buy_order", "issued", "location_id", "min_volume", "price", "range", 
    "system_id", DB::raw("SUM(volume_remain) vr"))->groupBy("type_id")        
     ->havingRaw("vr <= ?",['specific sum']);
    

    specific sum - 将是不会超过的数量。将其替换为您的相关金额。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 2021-07-11
      相关资源
      最近更新 更多