Hi Friends,
As you know GROUP BY is used to group the result-set by one or more columns. The SQL query to fetch the total views of blogs created at same day will be:
SELECT date(created_at) as creation_date, sum(view) as total_views
FROM blogs
GROUP BY date(created_at)
Similarly we can use GROUP BY in Rails as:
Blog.select("date(created_at) as creation_date, sum(views) as total_views").group("date(created_at)")
If we want total of grouped items in a single query we will write as:
Blog.group(:status).count
# => { 'draft' => 10, 'unapproved' => 3, 'published' => 7 }
Hope you liked this.
0 Comment(s)