Question

I have a table metrics which has the following columns :

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

Now I can find out how many new or old members are there by running a query like this :

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

This will give me the following result:

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

But along with this I want output like this :

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

Total is sum of all rows statisfying where clause above. How do I need to modify my previous query to get the result I need? Thanks.

Was it helpful?

Solution

You can do something like this:

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

Check it: http://sqlfiddle.com/#!15/b97a4/9 This is compact variant and includes the 'member' constant only once.

OTHER TIPS

The window-function using variant:

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

This can do what you want:

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;

See sqlfiddle http://sqlfiddle.com/#!2/0240b/5.

An advantage of this approach in comparison to using the subquery is that the sql finding the total count will not be run for each row of the sql defining the count by stage.

Try this code:

select (select count(*) as total from metrics where name = 'member' group by name),stage, count(*) from metrics where name = 'member' group by stage;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top