I am trying to use multiple Count and Sum commands in a single query.
However what is happening is when i use the following:
SUM(amount AND type = "dispute") as charge
It actually counts the amount of records and does not total the amounts.
What i want to do is use SUM with a where clause multiple times, so for example:
`$query = DB::table('cash_table')
->where('transaction_created', '>=', Carbon::now()->startOfWeek())
->select(DB::raw('
SUM(amount) as transaction_amount,
COUNT(amount) as transaction_count,
SUM(amount) WHERE type = "dispute" as charge_amount
COUNT(amount) WHERE type = "dispute" as charge_count
SUM(loan_amount) WHERE type = "loan" as loan_amount
COUNT(loan_amount) WHERE type = "loan" as loan_count
'))
->groupBy('transaction_created')
->get();`
The top two "transaction_amount & transaction count work fine as there is no where clause" The other don’t.
2
Answers
Try below:
Try below!