tob88
tob88

Reputation: 2211

Grouping by Different Date Ranges

I am trying to find the most efficient method to query my table and build a hash of the amount of users created between now and different date ranges. This hash should appear as follows...

{"7 Days" => 8, "1 Month" => 15, "3 Months" => 45, "12 Months" => 108, "Total" => 333}

Upvotes: 1

Views: 75

Answers (2)

John C
John C

Reputation: 4396

One way would be to create a scope.. An example of a scope that returned all instances less than a month old would be as follows:

scope :1month, -> { where("created_at < ?", 1.month.ago) }

You could then chain it with count.

n = MyClass.1month.count

Upvotes: 0

lx00st
lx00st

Reputation: 1596

You can make a view in a database in a way:

select (select count from now till now-7 days) as 7days,
       (select count from now till now - 1month) as 1month, etc

and then query that view in your app

Upvotes: 1

Related Questions