基于另一个表的组数据的PostgreSQL计数数据导致JSON

时间:2018-11-02 16:37:38

标签: json postgresql

我有两个看起来像这样的表:

users
id     name     city           state
1      Bob      Los Angeles    California
2      Susan    Dallas         Texas
3      Joe      Los Angeles    California


activity       
type           user_id
Activation     1
Registration   1
Activation     2
Activation     3

我想计算number of times the activity of type Activation已发生,以返回这样的数据集:

[
  {count: 2, city: 'Los Angeles', state: 'California'},
  {count: 1, city: 'Dallas', state: 'Texas'}
]

这是我尝试过的查询:

SELECT COUNT(*) AS count, user_id,
(SELECT json_agg(users.*) FROM users WHERE activity.user_id = users.id) as users
FROM activity
WHERE type='Activation'
GROUP BY users.city, users.state, user_id

我得到这个错误: error: missing FROM-clause entry for table "users"

我不确定如何对来自多个表的数据进行这种计数。

这是Postgresql的最新版本

2 个答案:

答案 0 :(得分:1)

我首先创建一个提供正确数据的视图,例如:

CREATE VIEW activations_on_locations AS
    SELECT count(*), U.city, U.state
    FROM users U
    INNER JOIN activity A
        ON U.id = A.user_id
        AND A.type='Activation'
    GROUP BY U.city, U.state;

反对JSON查询非常简单:

SELECT json_agg(AOL) FROM activations_on_locations AOL;

答案 1 :(得分:1)

您可以执行以下操作以获取所需的输出:

SELECT json_agg(users.*) from (select 
 COUNT(id) count, min(city) city, min(state) state from users, activity
where users.id=activity.user_id group by id, city, state) as users;