简体   繁体   中英

Laravel Group By and Sum per grouped rows

My Goal

I wish to group orders by their "type_id", and calculate the sum of the "volume_remain" per group of orders. I'm looking for a query to do this. Maybe it's worth mentioning that my orders table contains about 200.000 rows.

I working with the Laravel framework(5.8) and I am inexperienced with queries that are not of a very basic nature. Because of my lack of experience I haven't tried much.

This is how my orders table is build up.

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 : represents an item in a game

order : represents 1 order for a specific item on the ingame market

volume_remain : volume of items of that specific order that are still on the market

So each order belongs to a type_id, and a type_id can have many orders.

Desired Result

My desired result would be a collection of orders grouped by their type_id, but only orders that don't exceed a specific sum of their volume_remain.

You can query something like this

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 - will be that amount by which it won't exceed. Replace it with your relevant amount.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM