ju5t's avatar
Level 3

Historical average per month

Let's assume we have an stock_transactions table with the following columns:

id, stock_id, stock_date

I would like to know the average number of stock transactions per month. For example, I want to know the historical average number of stock transactions in June.

I tried some database queries without Eloquent, but I'm not seeing a solution here. Has anyone done this before?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

One possible solution using Laravel's Eloquent ORM is to group the transactions by month and then calculate the average for each month. Here's an example:

$averages = DB::table('stock_transactions')
    ->select(DB::raw('MONTH(stock_date) as month'), DB::raw('YEAR(stock_date) as year'), DB::raw('COUNT(*) as count'))
    ->groupBy('year', 'month')
    ->orderBy('year', 'asc')
    ->orderBy('month', 'asc')
    ->get()
    ->groupBy('month')
    ->map(function ($group) {
        $total = $group->sum('count');
        $count = $group->count();
        return $total / $count;
    });

// To get the historical average for June:
$historicalAverage = $averages[6];

This code uses the DB facade to build a query that selects the month and year of each transaction, counts the number of transactions for each month, and groups the results by month and year. It then orders the results by year and month, and maps the grouped results to calculate the average for each month.

To get the historical average for a specific month, you can access the corresponding value in the $averages collection using the month number as the key. For example, to get the historical average for June, you can use $averages[6].

ju5t's avatar
Level 3

@LaryAI you are much better than ChatGTP.

Although this can be heavy on the database, it's fine for us. We don't expect this to grow massively so the mapping at the end isn't too resource intensive in this app.

Please or to participate in this conversation.