Ruby Gem Sequel - how to show only group by with count value > 1

Viewed 232

With

DB[:items].group_and_count(:name).all

I get a list of names with the number of occurances.

What do I need to do if I only want those names returned (incluing their count) that have a count of more than e.g. 2? In SQL I would do something like this:

SELECT name, count(name) FROM items GROUP BY name HAVING count(name) > 2
2 Answers

You just have to add the having clause, that can be done in more than one way in Sequel.

# This uses virtual row as it is called in Sequel, with the { and }
DB[:items].group_and_count(:name).having{Sequel.function(:count, :name) > 2}.all

# or like this if you prefer
DB[:items].group_and_count(:name).having{COUNT(name) > 2}.all

what about this?

DB[:items].group('name').having('COUNT(name) > 2')
Related