什么是创建数据范围计数的更有效方法?

时间:2017-03-21 05:29:39

标签: sql postgresql

"通过ip分组数据然后计算重复次数。超过1次访问,超过2次访问,超过5次访问,超过10次访问。"

我最终编写了看起来像这样的查询

select (select count(*) from (select ip_agent_md5, count(*) as cnt from $table group by ip_agent_md5 having count(*) > 1)) as over_1_visit \
, (select count(*) from (select ip_agent_md5, count(*) as cnt from $table group by ip_agent_md5 having count(*) > 2)) as over_2_visits \
, ... from my_table;

如果我仍然需要在一个查询中内联它,那么写一个更有效的方法是什么?

1 个答案:

答案 0 :(得分:2)

SELECT some_column, sum(case when cnt > 1 then 1 else 0 end) as over_1,
                    sum(case when cnt > 3 then 1 else 0 end) as over_3
FROM
(
    SELECT some_column, COUNT(*) as cnt
    FROM some_table
    GROUP BY some_column
) x