Search code examples
phpsqlmysqllaravelgroup-by

groupby sum and count tickets


I am learning to use groupBy.

In my exercise, I must count the number of tickets that were sold and add the total money collected.

$tickets = Ingresostaquilla::groupBy('tipo')
    ->selectRaw('count(*) as quantity, tipo')
    ->get();

query result

I did the count by type of ticket, but I don't know how to make it add up to the total amount of money that each ticket collects.

Model table:

table data

I should use SUM, but how do I do it with groupBy?


Solution

  • $tickets = Ingresostaquilla
            ->selectRaw('tipo, sum(cantidad) as quantity, sum(total)')
            ->groupBy('tipo')
            ->get();  
    

    You can try this query, it will sum the amount of money raised for each type of ticket.