Group sql queries using age range laravel sql

Viewed 25

I am trying to group all my records based on age groups and gender. I have a date of birth and a sex field and would like to return something like this;

Age group         Value
Male 20 to 40       10
Female 20 to 40     22
Male 41 to 60       32
Female 41 to 60     29

I was able to get it working using this piece of code below but i need something performant using a raw sql statement

 $result = [];

        $age_range = ['18-25' => [18, 25], '26-35' => [26, 35], '36-45' => [36, 45], '46-55' => [46, 55], '56-65' => [56, 65]];

        foreach ($age_range as $key => $value) {
            $result_male_age = MasterRecord::select('id')->where('sex', 'Male')->whereBetween('date_of_birth', [now()->subYears($value[1]), now()->subYears($value[0])])->count('id');
            $result_female_age = MasterRecord::select('id')->where('sex', 'Female')->whereBetween('date_of_birth', [now()->subYears($value[1]), now()->subYears($value[0])])->count('id');
            $result[] = ['age_range' => $key, 'male' => $result_male_age, 'female' => $result_female_age];
        }

        $result_male_age = MasterRecord::where('sex', 'Male')->whereBetween('date_of_birth', [now()->subYears(6), now()->subCentury()])->count('id');
        $result_female_age = MasterRecord::where('sex', 'Female')->whereBetween('date_of_birth', [now()->subYears(6), now()->subCentury()])->count('id');
        $result[] = ['age_range' => '65 and above'] ;

        $result[] = ['age_range' => $key, 'male' => $result_male_age, 'female' => $result_female_age];
        
        return $result;

I would like to do a selectRaw sql statement as that guarantees performance as the records would be about 500,000 records. How would i write such sql query? Any help would be appreciated

0 Answers
Related