1

I have a query with the following structure -

select a.a1,b.b1,c.c1,d.d1,
        count(e.e1) over (partition by e.e2)
from a join b
 on a.aid = b.bid
 join c
 on b.bid = c.cid
 join e
 ......many other joins;

The problem is that I want to do something like count(e.e1) over (partition by e.e2 where e.e2 = 'mouse')

I mean I want to partition by the e2 column but consider one of the partitions.

For example, if e2 columns had the following values - "mouse", "cat" and "dog". Then the above query would give an output resembling the following -

a11 b11 c11 d11 4  -> record for "mouse" 
a11 b11 c11 d11 5  -> record for "cat"
a11 b11 c11 d11 7  -> record for "dog" 

Now, I don't want the records for "cat" and "dog". I only want for "mouse". Any suggestions?

2
  • 2
    Can you add some sample data and the expected output based on that sample data? I don't really understand your question Commented Mar 6, 2015 at 15:31
  • Sure. Let me do that. Commented Mar 7, 2015 at 15:52

1 Answer 1

2

I think you want conditional aggregation:

select sum(case when e2 = 'mouse' then 1 else 0 end) over ()

This puts the number of "mouse"s on each row in the result set.

EDIT:

If it is based on the column, then you just want:

select count(*) over (partition by e2)
Sign up to request clarification or add additional context in comments.

3 Comments

Also, even easier is select sum((e2='mouse')::integer)
Thanks for your reply. Please see the updated question for more clarification.
If I do as it says in the edit, then the response would be contain rows for "cat", "dog" and "mouse"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.