表中的多级聚合

时间:2014-05-13 05:13:18

标签: sql postgresql

我有一个表格指标,其中包含以下列:

stage  name
---------------------
new    member
new    member
old    member
new    visitor
old    visitor

现在我可以通过运行这样的查询找出有多少新成员或旧成员:

select stage, count(*) from metrics where name = 'member' group by stage;

这将给我以下结果:

stage count
-----------
new   2
old   1

但除此之外,我想要这样的输出:

total  stage count
------------------
3     new    2
3     old    1

总计是满足上述where子句的所有行的总和。我如何修改以前的查询以获得我需要的结果?感谢。

4 个答案:

答案 0 :(得分:2)

您可以这样做:

with t as 
 (select stage from metrics where name = 'member')
select 
 (select count(*) from t) as total,
 stage, count(*) 
from t
group by stage

检查一下:http://sqlfiddle.com/#!15/b97a4/9 这是紧凑型变体,仅包含'member'常量一次。

答案 1 :(得分:2)

window-function使用变体:

with member as (
  select stage, count(*)
  from metrics where name = 'member'
  group by stage
)
select sum(count) over () as total, member.*
from member

http://sqlfiddle.com/#!15/b97a4/18

答案 2 :(得分:0)

这可以做你想要的:

SELECT t2.totalCount,
  t1.stage,
  t1.stageCount
FROM
  (SELECT stage,
    COUNT(*) stageCount
  FROM metrics
  WHERE name = 'member'
  GROUP BY stage
  ) t1,
  (SELECT COUNT(*) AS totalCount FROM metrics WHERE name = 'member'
  ) t2;

请参阅sqlfiddle http://sqlfiddle.com/#!2/0240b/5

与使用子查询相比,这种方法的一个优点是,不会为定义逐个计数的sql的每一行运行找到总计数的sql。

答案 3 :(得分:0)

试试这段代码:

select (select count(*) as total from metrics where name = 'member' group by name),stage, count(*) from metrics where name = 'member' group by stage;