PostgreSQL合并计数和分组结果
上述SQL查询提供以下输出:PostgreSQL合并计数和分组结果,sql,postgresql,postgresql-9.5,Sql,Postgresql,Postgresql 9.5,上述SQL查询提供以下输出: select type, created_at::date , count(type) from txns group by created_at::date, type order by created_at::date; type | created_at | count ---------+------------+------- full | 2017-05-20 | 2 virtual | 2017-05-20 | 2
select type, created_at::date , count(type)
from txns
group by created_at::date, type
order by created_at::date;
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\u at
对上述结果进行分组,以获得以下输出:
select type, created_at::date , count(type)
from txns
group by created_at::date, type
order by created_at::date;
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 | full_count | virtual_count
------------+-----------------
2017-05-20 | 2 | 2
2017-05-21 | 1 | 1
2017-05-22 | 3 | 0
如果您有两种以上的类型,并且在进一步处理过程中,您可以处理hstore:
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)
我将在不使用CTE/子查询的情况下执行此操作,如下所示:
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;
Postgres通常实现CTE,因此这甚至可能有轻微的性能优势
注意:您也可以在较新版本的Postgres中使用过滤器
:
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;
你太棒了,谢谢!等待其他结果其他方面我会接受它非常感谢。这个解决方案更好,而且“类型”不应该在组中。