我正在postgres的hstore列中收集项目和版本号列表。我有兴趣看到100个最常见的键值对。例如,如果这是我的数据集:
"foo"=> "22",
"foo"=> "33",
"bar"=> "55",
"baz"=> "77",
"foo"=> "22"
我想知道"foo"=>"22"
是我数据库中最常用的键/值对。让我们说一下,为了便于讨论表名为widgets
且hstore列名为items
的问题。
select ??? from widgets;
是否可以仅使用SQL获取顶部键值对的列表?
答案 0 :(得分:2)
要将键/值对作为一个集合,相关函数为each()
:
select * from each('a=>1,b=>2')
http://www.postgresql.org/docs/current/static/hstore.html#HSTORE-FUNC-TABLE
带限制的简单计数可以解决问题:
SELECT (item).key, (item).value, count(*) as count
FROM (SELECT each(items) as item FROM widgets) as t
GROUP BY (item).key
ORDER BY 2 DESC, (item).value
LIMIT 100
如果您只对密钥感兴趣,可以使用更简单的skeys()
代替:
SELECT k, count(*) as count
FROM (SELECT skeys(items) as k FROM widgets) as t
GROUP BY k
ORDER BY 2 DESC, k
LIMIT 100
答案 1 :(得分:1)
哦,这很容易。这里:
SELECT key, count(*) FROM
(SELECT (each(h)).key FROM reports)
AS stat
GROUP BY key
ORDER BY count DESC, key
LIMIT 100;
答案 2 :(得分:1)
当您在完整的键/值对之后,应执行以下操作:
select items, count(*) as cnt
from widgets
group by items
order by 2 desc
limit 100