我有一张桌子
id | registeredAt | organisationId |
=====================================
int | timestamptz | int |
-------------------------------------
对于每个组织,我希望在白天完成注册计划。
E.g。
organisationId | registrations
=================================================================
1 | [ {"date": "...", "registrations": 10}, {... ] |
------------------------------------------------------------------
2 | [ {"date": "...", "registrations": 12}, {... ] |
------------------------------------------------------------------
现在我可以在几个单独的查询中执行此操作(每个组织一个)使用:
select count(*) as "registrations", date_trunc('day', "registeredAt") as date
from my_table
where "organisationId" = 1
group by date;
并将其映射到每个organisationId
,但我想知道在postgresql中运行这一切是否会更有效率。问题是我无法弄清楚如何正确地聚合数据以获得我想要的东西(这基本上是每个组织的注册直方图)。
PS。 接下来,我不确定如何构建一个查询,这个查询会在没有注册的日子里给我零,但这是一个小问题。
答案 0 :(得分:0)
尝试:
CREATE TYPE myrowtype AS ("date" date, registrations int);
SELECT organizationId, array_agg( row( registeredAt, cnt )::myrowtype ) as Registrations
FROM (
select organizationId, date_trunc('day', registeredAt) as registeredAt, count(*) As cnt
from my_table
group by organizationId, date_trunc('day', registeredAt)
) x
GROUP BY organizationId
ORDER BY 1
如果您想以JSON格式获得结果(如问题所示),请使用:
SELECT organizationId, json_agg( row( registeredAt, cnt )::myrowtype ) as Registrations
FROM (
select organizationId, date_trunc('day', registeredAt) as registeredAt, count(*) As cnt
from my_table
group by organizationId, date_trunc('day', registeredAt)
) x
GROUP BY organizationId
ORDER BY 1