Re: [GENERAL] count case when - PG 9.2 - Mailing list pgsql-general

From vinny
Subject Re: [GENERAL] count case when - PG 9.2
Date
Msg-id 73ce6477fe28b4db13cb319f34a6ce96@xs4all.nl
Whole thread Raw
In response to [GENERAL] count case when - PG 9.2  (Patrick B <patrickbakerbr@gmail.com>)
Responses Re: [GENERAL] count case when - PG 9.2
List pgsql-general
On 2017-03-09 05:27, Patrick B wrote:
> Hi guys. How can I count using 'CASE WHEN'?
>
> Example:
>
>>> SELECT
>>
>>> CASE
>>
>>> WHEN AND c.regdate > EXTRACT(epoch FROM (now() - INTERVAL
>>> '14 day'))
>>
>>> THEN 'trial'
>>
>>> WHEN last_pay > EXTRACT(epoch FROM (now() - INTERVAL '37
>>> day'))
>>
>>> THEN 'paying'
>>
>>> END as account_status,
>>
>>> c.id [1]
>>
>>> FROM public.clients c
>>
>>> WHERE (
>>
>>> (last_pay > EXTRACT('epoch' FROM now() - '12
>>> Months'::INTERVAL))
>>
>>> )
>>
>>> ORDER BY 1
>  I wanna know how many of 'trial' and 'paying' customers the query
> returns. can you guys please advice how to do it?
>
> Thanks
> Patrick
>

comparisons like "A>B" return a boolean. Booleans can be cast to
integers, and integers can be summed.

SUM((A>B)::int)

But depending on the situation, indexes etc it could be faster to run e
separate count query, you'll have to test that.


pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: [GENERAL] Unable to start postgresql
Next
From: mac pack
Date:
Subject: [GENERAL] Recovery damaged dump file