我遇到了一些我认为很简单的事情......
我有一个简单的模型Statistic
,用于存储日期(created_at
),user_fingerprint
和structure_id
。从那时起,我想创建一个图表来显示每天#visitors。
所以我做了
@structure.statistics.order('DATE(created_at) ASC').group('DATE(created_at)').count
哪种方法有效并返回我的期望:
=> {Sat, 18 May 2014=>50, Mon, 19 May 2014=>90}
现在我也喜欢这样,但我想用同一对(created_at
,user_fingerprint
)挤压所有行。例如:
| created_at | user_fingerprint | structure_id |
|----------------------|------------------|--------------|
| Sat, 18 May 2014 2PM | '124512341' | 12 |
| Sat, 18 May 2014 4PM | '124512341' | 12 |
| Mon, 19 May 2014 6PM | '124512341' | 12 |
有了这些数据,我会:
=> {Sat, 18 May 2014=>1, Mon, 19 May 2014=>1}
# instead of
=> {Sat, 18 May 2014=>2, Mon, 19 May 2014=>1}
我可以在Ruby中完成它,但我想知道我是否可以直接使用SQL& AREL。
这是我最后所做的:
@impressions = {}
# The following is to ensure I will have a key when there is no stat for a day.
(15.days.ago.to_date..Date.today).each { |date| @impressions[date] = 0 }
@structure.statistics.where( Statistic.arel_table[:created_at].gt(Date.today - 15.days) )
.order('DATE(created_at) ASC')
.group('DATE(created_at)')
.select('DATE(created_at) as created_at, COUNT(DISTINCT(user_fingerprint)) as user_count')
.each{ |stat| @impressions[stat.created_at] = stat.user_count }
我需要做一些Ruby,但这对我有好处。
答案 0 :(得分:1)
您的查询看起来像(Oracle方言)
select trunc(created_at), user_fingerprint, count(distinct user_fingerprint)
from statistic
group by trunc(created_at), user_fingerprint
没有用于从日期时间数据字段中获取日期部分的SQL标准。
oracle:trunc(dt_column) sql server:cast(dt_column As Date) mysql:DATE(dt_column)
答案 1 :(得分:1)
@structure.statistics.order('DATE(created_at) ASC').group('DATE(created_at)').select('count(distinct(user_fingerprint)) as user_count').first.user_count