Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9055501
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T13:58:06+00:00 2026-06-16T13:58:06+00:00

I’m trying to do a cohort analysis query in Rails but running into trouble

  • 0

I’m trying to do a cohort analysis query in Rails but running into trouble with the correct way to group by the last action date.

I want to end up with rows of the following data for something like this: http://www.quickcohort.com/

count first_action last_action

for all users who registered in the last year. first_action and last_action are truncated to the nearest month.

Getting the counts grouped by the first_action is easy enough, but when I try to extend it to include the last_action I encounter

ActiveRecord::StatementInvalid: PGError: ERROR:  aggregates not allowed in GROUP BY clause

Here’s what I have so far

User
  .select("COUNT(*) AS count,
    date_trunc('month', users.created_at) AS first_action,
    MAX(date_trunc('month', visits.created_at)) AS last_action # <= Problem
  ")
  .joins(:visits)
  .group("first_action, last_action") # TODO: Subquery ?
  .order("first_action ASC, last_action ASC")
  .where("users.created_at >= date_trunc('month', CAST(? AS timestamp))", 12.months.ago)

The visits table tracks all visits users make to the site. Using the latest visit as the last action seems like it should be easy, but I’m having trouble forming it into SQL.

I’m also open to other solutions if there are better ways, but it seems like a single SQL query would be most performant.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T13:58:07+00:00Added an answer on June 16, 2026 at 1:58 pm

    I think you need to do this in a subquery. Something like:

    select first_action, last_action, count(1)
    from (
        select
            date_trunc('month', visits.created_at) as first_action,
            max(date_trunc('month', visits.created_at)) as last_action
        from visits
        join users on users.id = visits.user_id
        where users.created_at >= ?
        group by user_id
    )
    group by first_action, last_action;
    

    I’m not sure what the most elegant way would be to do this in ARel, but I think it’d be something like this. (Might just be easier to use the SQL directly.)

    def date_trunc_month(field)
      Arel::Nodes::NamedFunction.new(
        'date_trunc', [Arel.sql("'month'"), field])
    end
    
    def max(*expressions)
      Arel::Nodes::Max.new(expressions)
    end
    
    users = User.arel_table
    visits = Visit.arel_table
    
    user_visits = visits.
        join(users).on(visits[:user_id].eq(users[:id])).
        where(users[:created_at].gteq(12.months)).
        group(users[:id]).
        project(
            users[:id],
            date_trunc_month(visits[:created_at]).as('first_visit'),
            max(date_trunc_month(visits[:created_at])).as('last_visit')
        ).
        as('user_visits')
    
    cohort_data = users.
        join(user_visits).on(users[:id].eq(user_visits[:id])).
        group(user_visits[:first_visit], user_visits[:last_visit]).
        project(
            user_visits[:first_visit],
            user_visits[:last_visit],
            Arel::Nodes::Count.new([1]).as('count')
        )
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a French site that I want to parse, but am running into
I'm trying to select an H1 element which is the second-child in its group
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I am currently running into a problem where an element is coming back from
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I want to count how many characters a certain string has in PHP, but
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.