How can I count the number of records that have a unique value in a particular field in ROR?

前端 未结 7 1076
予麋鹿
予麋鹿 2020-12-04 21:21

I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.

Something like:

Record         


        
7条回答
  •  长情又很酷
    2020-12-04 22:04

    As I mentioned here, in Rails 4, using (...).uniq.count(:user_id) as mentioned in other answers (for this question and elsewhere on SO) will actually lead to an extra DISTINCT being in the query:

    SELECT DISTINCT COUNT(DISTINCT user_id) FROM ...

    What we actually have to do is use a SQL string ourselves:

    (...).count("DISTINCT user_id")

    Which gives us:

    SELECT COUNT(DISTINCT user_id) FROM ...

提交回复
热议问题