Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • GROUP BY clause in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 500
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: