4

I'm using

SELECT DISTINCT ON() 

to return a particular row from a group of rows. Works well. But what I also want to return is the "COUNT(*)". So it might look like

SELECT DISTINCT ON(name)
  name, num_items, COUNT(name)
FROM customers
ORDER BY name, num_items DESC

But of course, I get an error saying "name should be in a GROUP BY aggregate function".

How can I achieve the same result with the "count()" included?

1 Answer 1

4

you can use count as window function:

select distinct on (name)
    name, num_items, count(*) over(partition by name)
from customers
order by name, num_items desc;

or in your case you can just use group by name and use simple aggregation:

select
    name, max(num_items), count(*)
from customers
group by name
order by name

sql fiddle demo

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

Comments

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.