我記錄了用戶觀看一系列視頻的次數。現在我正在試圖製作每天觀看任何視頻的用戶數量。導軌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
這是更好的方式 - 感謝 – Edward 2013-02-27 15:17:02
在軌道4,5看到http://stackoverflow.com/a/棄用19362288/670433爲使用ModelName.distinct.count(:attribute_name)的解決方案 – s2t2 2014-02-07 22:39:39
如何返回模型的所有屬性? – 2014-10-09 18:20:40