June 04 2014

multiple counts with one SQL Query

Tagged Under : ,

MySQL
It have few ways to get multiple counts with one SQL Query. But, it also will return more then one row records to user, and also the total count wouldn’t appear if it no inside the records.

In the same time, user need did few times loop and if else conditions to get the results. It will slow down the application performance and give developer more job to completed the job.

In here, I have a better way to process multiple counts with one SQL Query and it just return one row record only.

Let’s see below example how the SQL look like:
SELECT date, 
  SUM(case when `status` = 'approved' then 1 else 0 end) as ApprovedCount,
  SUM(case when `status` = 'rejected' then 1 else 0 end) as RejectedCount,
  SUM(case when `status` = 'pending' then 1 else 0 end) as PendingCount,
FROM table
GROUP BY date

From Above example we can get multiple count in one rows with the date. It more easy than we need to write the extra code to get the results.

Make a Comment

*

code