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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.