Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

397
Views
How to create JSON format with group by and count functions in mysql?

I need to get count of group by key as an array of json.

table:

designation      | name  
------------------------
Engineer         | Ben      
Sr.Engineer      | Tom      
Lead Engineer    | Dan
Engineer         | Michle  

output that I need:

grouped_data

[{designation:"Engineer",count:2},{designation:"Sr.Engineer",count:1}, {designation:"Lead Engineer",count:1}]

I tried

SELECT JSON_ARRAYAGG(JSON_OBJECT('designation', designation,  'total_users', count(*) as total_users)) as user_spit_up
FROM user group by designation

But its getting error

Invalid use of group function.

Help please. Thanks in advance,

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I had the same problem and this was the solution that worked for me. For your problem it would be something like this:

SELECT JSON_ARRAYAGG(a.array_counts)
FROM (SELECT JSON_OBJECT(
                     'designation', designation,
                     'total_users', COUNT(designation)
                 ) array_counts
      FROM user
      GROUP BY designation
     ) a
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!