我有一张表,我计算一个元素出现的频率。为此,我可以使用Sequel::Dataset#group_and_count
.
但现在我想计算这个结果。我怎样才能做到这一点?
例子
require 'sequel'
Sequel.extension :pretty_table
DB = Sequel.sqlite()
DB.create_table( :test ){
add_field :key, :type => :nvarchar, :size => 10
add_field :value, :type => :nvarchar, :size => 10
}
'a'.upto('f'){|a|
a.upto('x'){|b|
DB[:test].insert( :key => a, :value => b)
}
}
sel = DB[:test].group_and_count(:key)
puts Sequel::PrettyTable.string(sel)
这给了我:
+-----+---+
|count|key|
+-----+---+
| 24|a |
| 23|b |
| 22|c |
| 21|d |
| 20|e |
| 19|f |
+-----+---+
现在我想计算一个计数值出现的频率。
我的结果应该是:
+-----------+-----+
|count_value|count|
+-----------+-----+
| 24 | 1 |
| 23 | 1 |
| 22 | 1 |
| 21 | 1 |
| 20 | 1 |
| 19 | 1 |
+-----------+-----+
我可以得到这个结果:
mycount = Hash.new(0)
DB[:test].group_and_count(:key).each{| res |
mycount[res[:count]] += 1
}
p mycount # {24=>1, 23=>1, 22=>1, 21=>1, 20=>1, 19=>1}
使用 SQL(请参阅SQL Group by Count of Counts)我可以执行以下命令:
puts DB.fetch(<<-sql ).all
select count_value, count(*) as count from (
select count(*) as count_value from test group by key
)
group by count_value
sql
但我正在寻找一种使用 Sequel 命令(如果可能的话)来执行此操作的方法。
我尝试了什么:
group_and_count
不可链接:
#SQLite3::SQLException: no such column: count (Sequel::DatabaseError)
sel = DB[:test].group_and_count(:key).group_and_count(:count)
也无法重命名 :count
sel = DB[:test].group_and_count(:key).select(:count.as(:count_value))
如果我定义一个视图,我会得到一个 DatabaseError:
DB.create_view(:count_testkey, DB[:test].group_and_count(:key))
sel = DB[:count_testkey].group_and_count(:count)
#SQLite3::SQLException: aggregate functions are not allowed in the GROUP BY clause (Sequel::DatabaseError)
puts Sequel::PrettyTable.string(sel)