rahul mishra
rahul mishra

Reputation: 1470

PostgreSQL merge COUNT and GROUP BY result

select type, created_at::date , count(type)
from txns
group by created_at::date, type
order by created_at::date;

The above SQL query gives the following output:

  type   | created_at | count 
---------+------------+-------
 full    | 2017-05-20 |     2
 virtual | 2017-05-20 |     2
 full    | 2017-05-21 |     1
 virtual | 2017-05-21 |     1
 full    | 2017-05-22 |     3

How can I group the above result by created_at to get the following output:

 created_at | full_count | virtual_count
------------+-----------------
 2017-05-20 |     2     |  2
 2017-05-21 |     1     |  1
 2017-05-22 |     3     |  0

I want to get the full and virtual type count by created_at in a single row.

Upvotes: 0

Views: 293

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1270391

I would do this without a CTE/subquery as:

select created_at::date,
       sum( (type = 'Full')::int ) as cnt_full,
       sum( (type = 'Virtual')::int ) as cnt_virtual
from txns
group by created_at::date
order by created_at::date;

Postgres often materializes CTEs, so this could even have a slight performance advantage.

Note: You can also use filter in more recent versions of Postgres:

select created_at::date,
       count(*) filter (where type = 'Full') as cnt_full,
       count(*) filter (where type = 'Virtual') as cnt_Virtual
from txns
group by created_at::date
order by created_at::date;

Upvotes: 0

n3ko
n3ko

Reputation: 415

If you have more then two types, and in further processing you can deal with hstore:

WITH q AS ( SELECT type, created_at::date , count(type) FROM txns GROUP BY 1,2)
SELECT created_at, hstore(array_agg(type), array_agg(count::text))
FROM q GROUP BY 1;

Upvotes: 0

Vao Tsun
Vao Tsun

Reputation: 51599

this should work:

with so as (
select type, created_at::date , count(type) from txns group by created_at::date, type order by created_at::date
)
 select
  created_at
, sum(case when type = 'full' then count else 0 end) full_count
, sum(case when type = 'virtual' then count else 0 end) virtual_count
from so
group by created_at;

 created_at | full_count | virtual_count
------------+------------+---------------
 2017-05-20 |          2 |             2
 2017-05-21 |          1 |             1
 2017-05-22 |          3 |             0
(3 rows)

Upvotes: 1

Related Questions