2013-02-27 106 views
12

我记录了用户观看一系列视频的次数。现在我正在试图制作每天观看任何视频的用户数量。导轨COUNT SELECT DISTINCT

UserVideoWatching.where("created_at >= ? AND user_id != ?",1.month.ago, User.elephant.id).group("DATE(created_at)").reorder('created_at').count 

产生SQL

SELECT COUNT(*) AS count_all, DATE(created_at) AS date_created_at FROM `user_video_watchings` WHERE (created_at >= '2013-01-27 10:43:24' AND user_id != 7) GROUP BY DATE(created_at) ORDER BY created_at 

产生的每一天的所有视频观看正确的结果,但我说我想只显示每个用户一次。

我想这些SQL

SELECT COUNT(DISTINCT user_id) AS count_all, DATE(created_at) AS date_created FROM `user_video_watchings` WHERE (created_at >= '2013-01-27 10:33:18' AND user_id != 7) GROUP BY DATE(created_at) ORDER BY created_at 

,所以我想

UserVideoWatching.where("created_at >= ? AND user_id != ?",1.month.ago, User.elephant.id).group("DATE(created_at)").reorder('created_at').select('COUNT(DISTINCT user_id) AS count_all, DATE(created_at) AS date_created') 

会做什么,我想要的。但是这给出了

[#<UserVideoWatching >, #<UserVideoWatching >] 

而不是散列。

任何想法?

我使用轨道3.1和MySQL

回答

26

您可以使用distinct.count(:attribute_name)

(在Rails 3用途:count(:user_id, distinct: true)代替)

这样:

UserVideoWatching.where("created_at >= ? AND user_id != ?", 1.month.ago, User.elephant.id) 
.group("DATE(created_at)").reorder('created_at').distinct.count(:user_id) 

无法测试,但我认为这会产生你之后的SQL。

+0

这是更好的方式 - 感谢 – Edward 2013-02-27 15:17:02

+2

在轨道4,5看到http://stackoverflow.com/a/弃用19362288/670433为使用ModelName.distinct.count(:attribute_name)的解决方案 – s2t2 2014-02-07 22:39:39

+0

如何返回模型的所有属性? – 2014-10-09 18:20:40

11

在Rails 4,使用(...).uniq.count(:user_id)在其他的答案中提到(对于这个问题,并在SO别处)实际上会导致额外的DISTINCT查询是:

SELECT DISTINCT COUNT(DISTINCT user_id) FROM ...

其实我们有做的是使用一个SQL字符串自己:

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

这给了我们:

SELECT COUNT(DISTINCT user_id) FROM ...

0

应该使用不同的,在导轨5.0.1,不同平等的uniq,但: [11] pry(main)> Needremember.distinct.count(:word) (1.1ms) SELECT DISTINCT COUNT(DISTINCT "needremembers"."word") FROM "needremembers" [12] pry(main)> Needremember.uniq.count(:word) DEPRECATION WARNING: uniq is deprecated and will be removed from Rails 5.1 (use distinct instead) (called from __pry__ at (pry):12) (0.6ms) SELECT DISTINCT COUNT(DISTINCT "needremembers"."word") FROM "needremembers"