Saturday, July 20, 2024

Calculate totals using conditional aggregates

select 
    count(case when status = 'Requested' then 1 end) as requested,
    count(case when status = 'Planned' then 1 end) as planned,
    count(case when status = 'Completed' then 1 end) and completed,
from features

on laravel

$status = Feature::toBase() // toBase we don't want to the Feature model return back, but instead we want collection of different totals
    ->selectRaw("count(case when status = 'Requested' then 1 end) as requested")
    ->selectRaw("count(case when status = 'Planned' then 1 end) as planned")
    ->selectRaw("count(case when status = 'Completed' then 1 end) as completed")
    ->first();

we also can improve to // filter will allow you to use where statement
$status = Feature::toBase()
    ->selectRaw("count(*) filter (where status = 'Requested') as requested")
    ->selectRaw(("count(*) filter (where status = 'Planned') as planned")
    ->selectRaw(("count(*) filter (where status = 'Completed') as completed")
    ->first();

No comments: