Re: COUNT() BASED ON MULTIPLE WHERE CONDITIONS

From: Michael Glaesemann <grzm(at)seespotcode(dot)net>
To: "(dot)(dot)(dot)tharas" <tharasp(at)gmail(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: COUNT() BASED ON MULTIPLE WHERE CONDITIONS
Date: 2009-05-17 14:15:38
Message-ID: 445FFF4A-1FD7-410B-A1EB-DB66AFF57C79@seespotcode.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice


On May 17, 2009, at 9:05 , ...tharas wrote:

> Required Result set*
>
> Year W_count T_count S_Count
> 2007 0 1 0
> 2008 3 1 1
> 2009 0 0 1
>
> I could write three separate queries for this like
>
> select count(PersonId) as W_count from my_table where Year =
> 2008
> and workstatus = 'W'
>
> can I get the whole result in a single query?

SELECT "year",
SUM(CAST((workstatus = 'W') AS INT)) AS w_count
SUM(CAST((workstatus = 'T') AS INT)) AS t_count
SUM(CAST((workstatus = 'S') AS INT)) AS s_count
FROM my_table
GROUP BY "year"

Michael Glaesemann
grzm seespotcode net

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Dallas Morisette 2009-05-17 14:16:17 Re: Include result of function call within WHERE clause in results
Previous Message Dallas Morisette 2009-05-17 14:12:55 Re: Include result of function call within WHERE clause in results