PostgreSQL合并COUNT和GROUP BY结果

时间:2018-05-23 08:37:08

标签: sql postgresql postgresql-9.5

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

上述SQL查询提供以下输出:

  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

如何通过created_at对上述结果进行分组 得到以下输出:

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

我想通过created_at在一行中获得fullvirtual类型计数。

感谢高级!

3 个答案:

答案 0 :(得分:1)

这应该有效:

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)

答案 1 :(得分:0)

如果你有两种以上的类型,并且在进一步处理中你可以处理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;

答案 2 :(得分:0)

我会在没有CTE /子查询的情况下执行此操作:

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经常实现CTE,因此这甚至可以带来轻微的性能优势。

注意:您还可以在更新版本的Postgres中使用filter

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;