2013-02-27 121 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"