Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails & Postgresql: how to group queries by hour?

How do I group by hour in Postgres & Rails? I've read through quite a few SO answers but I'm getting errors.

This works when grouping by date:

Model.group("date(updated_at)").count

Then I tried the following for hour but they didn't work:

Model.group("hour(updated_at)").count
Model.group("date_format(updated_at, '%H')").count
Model.group("extract(hour from updated_at)").count

Once I've found certain hours I need to update, how would I then get the models with those hours? I.e:

Model.where("hour(updated_at) = ?", 5)
like image 552
mind.blank Avatar asked Mar 03 '13 03:03

mind.blank


People also ask

What are Rails used for?

Rails is a development tool which gives web developers a framework, providing structure for all the code they write. The Rails framework helps developers to build websites and applications, because it abstracts and simplifies common repetitive tasks.

Is Rails a backend or frontend?

It does so by creating default structures for your code, your application's database and the web pages your application will serve up to the client. Seeing as Ruby on Rails runs on a web server and serves up information to client programs (web browsers), it's said to be a server-side or backend application.

What is Rails framework?

Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. It encourages and facilitates the use of web standards such as JSON or XML for data transfer and HTML, CSS and JavaScript for user interfacing.

What is Rails in it?

Rails is a framework for web application development written in Ruby. It provides a structure to web developers for all the codes. It is manufactured to ease web application programming by predicting what every developer needs to begin with.


1 Answers

You could try the following

Model.group("DATE_PART('hour', updated_at)").count

UPDATE:

How to find records

Model.where("DATE_PART('hour', updated_at) = ?", 5)
like image 191
jvnill Avatar answered Oct 31 '22 13:10

jvnill