PostgreSQL计数唯一性

时间:2019-11-18 21:18:14

标签: sql postgresql

我有一个pageviews结构,例如:

| main_group  | subgroup     | page  | uid   |  viewcount  |
-------------------------------------------------------------
| foo         | targeted     |  A    | 111   | 3           |
------------------------------------------------------------
| foo         | targeted     |  B    | 111   | 2           |
------------------------------------------------------------
| foo         | targeted     |  A    | 222   | 1           |
------------------------------------------------------------
| foo         | targeted     |  A    | 333   | 4           |
------------------------------------------------------------
| foo         | targeted     |  B    | 333   | 3           |
------------------------------------------------------------
| foo         | external     |  A    | 444   | 1           |
------------------------------------------------------------
| foo         | external     |  A    | 555   | 1           |
------------------------------------------------------------
| foo         | external     |  B    | 555   | 1           |
------------------------------------------------------------

所以uid代表浏览viewcount某个页面的次数的用户。但是我只希望 unique 用户计数,同时保留组,子组,页面信息。我想要这个结果:

| main_group  | subgroup     | page  | unique_viewcount  |
------------------------------------------------------------
| foo         | targeted     |  A    | 3                 |
------------------------------------------------------------
| foo         | targeted     |  B    | 2                 |
------------------------------------------------------------
| foo         | external     |  A    | 2                 |
------------------------------------------------------------
| foo         | external     |  B    | 1                 |
------------------------------------------------------------

我不知道如何编写select语句。我尝试过:

select count (distinct (page, uid)) as unique_viewcount, main_group, subgroup, page
from pageviews
group by (main_group, subgroup, page, uid);

但每个unique_viewcount是1

1 个答案:

答案 0 :(得分:0)

我认为您只想要count(distinct uid)

select main_group, subgroup, page, count(distinct uid) as unique_viewcount 
from pageviews
group by main_group, subgroup, page;
相关问题