Home > Software engineering >  Postgresql select items and sum of each of their statuses
Postgresql select items and sum of each of their statuses

Time:03-07

I am fed up with creating sql query to database table, which contains, let's say just three columns - id, title and status. What I need is write a select which shows total of all titles and their each and every status sum. Would appreciate any ideas.

Database:

ID Title Status
1 Title A Done
2 Title B Done
3 Title A Rejected
4 Title B Done
5 Title A Done
6 Title B Done
7 Title A Rejected
8 Title B Done

What I need is:

Title Done Rejected
Title A 6 2
Title B 8 0

Thanks in advance.

CodePudding user response:

SELECT Title,
   SUM(CASE WHEN Status='Done' THEN 1 ELSE 0 END)  as Done,
   SUM(CASE WHEN Status='Rejected' THEN 1 ELSE 0 END)  as Rejected
   FROM [Table] group by Title

thanks to

Sql Server equivalent of a COUNTIF aggregate function

  • Related