简体   繁体   English

Rails / SQL:如何订购分组记录

[英]Rails/SQL: How to order grouped records

I have a tabel called SessionHistory with the column of ip . 我有一个名为SessionHistory的表格,其中包含ip列。

I now want to first group the records having the same ip and then sort the groups by the number of records in each group. 我现在想首先对具有相同ip的记录进行分组,然后按照每个组中的记录数对组进行排序。

For Example: 例如:

Record1: ip = 3
Record2: ip = 1
Record3: ip = 2
Record4: ip = 1
Record5: ip = 2
Record6: ip = 1

grouped ... 分组......

Group1:
    Record1: ip = 3
Group2:
    Record2: ip = 1
    Record4: ip = 1
    Record6: ip = 1
Group3:
    Record3: ip = 2
    Record5: ip = 2

sorted ... 排序......

Group1:
    Record2: ip = 1
    Record4: ip = 1
    Record6: ip = 1
Group2:
    Record3: ip = 2
    Record5: ip = 2
Group3:
    Record1: ip = 3

My Approach: 我的方法:

        - @devices = SessionHistory.all.group_by(&:ip)
        - @devices.keys.sort.each do |ip| # not sorted after size of group!
            %h1= ip
            %h4= @devices[ip].first.name # somehow not giving anything!
            - @devices[ip].each do |session|
                %h1.tiny= session.name

There are some problems though, the groups are obviously not sorted after their size and I am not able to read values from single records in one group. 但是存在一些问题,这些组显然没有按照它们的大小排序,而且我无法从一个组中的单个记录中读取值。

Grouped SQL queries are returned as a Hash, where the keys are the values of IPs which records are grouped by and the values are the objects themselves. 分组SQL查询作为哈希返回,其中键是记录按组分组的IP值,值是对象本身。 To sort that kind of results you could use the .sort method to order by hash values count: 要对这种结果进行排序,您可以使用.sort方法按哈希值计数:

@devices = SessionHistory.all.group_by(&:ip)
@devices.sort!{|a,b| b.values.count <=> a.values.count }

Or reverse ordering as simple as calling .reverse 或者反向排序就像调用.reverse一样简单

@devices = SessionHistory.all.group_by(&:ip)
@devices.sort!{|a,b| b.values.count <=> a.values.count }.reverse!

Not an SQL solution, but at least it is clean and just works™ 不是SQL解决方案,但至少它是干净的,只是工作™

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM