0

Table

select * from hello;
 id | name 
----+------
  1 | abc
  2 | xyz
  3 | abc
  4 | dfg
  5 | abc
(5 rows)

Query

select name,count(*) from hello where name in ('abc', 'dfg') group by name;

 name | count 

------+-------

 dfg  |     1
 abc  |     3
(2 rows)

In the above query, I am trying to get the count of the rows whose name is in the tuple. However, I want to get the id as well with the count of the names. Is there a way this can be achievable? Thanks

2 Answers 2

2

If you want to return the "id" values, then you can use a window function:

select id, name, count(*) over(PARTITION BY name)
from hello 
where name in ('abc', 'dfg');

This will return the id values along with the count of rows per name.

Sign up to request clarification or add additional context in comments.

4 Comments

PARTITION BY name will create a temporary internal table?
I'm not sure how Postgres handles it internally. PARTITION BY just processes a specified group of rows (a window) and returns an output for that current row. You're right, I forgot to take out the GROUP BY.
@wonder: no, it will not create a temporary table. It's different type of aggregation: postgresql.org/docs/current/static/tutorial-window.html
@a_horse_with_no_name If I am getting it correctly, postgres fetches all the rows with the names given in the tuple and then performs a count for each of the ones which has same name.
1

If you want to see all IDs for each name, you need to aggregate them:

select name, count(*), array_agg(id) as ids
from hello 
where name in ('abc', 'dfg') 
group by name;

This returns something like this:

name | count | ids    
-----+-------+--------
abc  |     3 | {1,3,5}
dfg  |     1 | {4}    

1 Comment

Thanks for this approach as well.

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.