我的links
表包含url
列和created_at
列,例如:
url | created_at
ex2.com | 2
ex1.com | 3
ex2.com | 1
ex1.com | 4
ex3.com | 5
我想按网址对其进行分组,统计此网址并按组中第一个网址的url_count和created_at排序,结果将是:
url | url_count
ex2.com | 2
ex1.com | 2
ex3.com | 1
我做Link.select(:url).group(:url).order('count_url DESC').count
现在我只需要按created_at排序,但我在此查询中丢失了它的值。
我该怎么做?
答案 0 :(得分:0)
您可以在Model.select
中传递多个列,例如:
Link.select("url, created_at, count(*) as count_url").group("url").order("created_at")
http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
答案 1 :(得分:0)
使用窗口函数我会:
select distinct url,count(url) over (partition by url) from a
-------------------
url | url_count
ex2.com | 2
ex1.com | 2
ex3.com | 1
如果你能把它翻译成红宝石......