sql - 按 hstore 中任意属性的值排序

标签 sql postgresql hstore

我有这样的记录:

id, hstore_col
1,  {a: 1, b: 2}
2,  {c: 3, d: 4}
3,  {e: 1, f: 5}

如何在 hstore 中为 any 属性按最大/最小值对它们进行排序?

结果应该是这样的(从小到大排序):

id, hstore_col
1,  {a: 1, b: 2}
3,  {e: 1, f: 5}
2,  {c: 3, d: 4}

我知道,我只能按这样的特定属性对它们进行排序:my_table.hstore_fields -> 'a',但这对我的问题不起作用。

最佳答案

使用 avals 转换为数组并将生成的数组从文本转换为整数。然后对数组进行排序,并按排序数组的第一个元素对结果进行排序。

select * from mytable
order by (sort(avals(attributes)::int[]))[1]

http://sqlfiddle.com/#!15/84f31/5

关于sql - 按 hstore 中任意属性的值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26591244/

相关文章:

ruby-on-rails - 在 Rails 中使用带有 Postgres HSTORE 的商店

ruby-on-rails - 如何为 Ruby on Rails fixtures YAML 文件中的 HStore 字段设置默认值?

PHP PDO 没有活跃的事务

sql - 复制 Azure SQL 数据库并更改规模

sql - 计算重复项时自加入 vs 分组

postgresql - 错误 : type "dblink_pkey_results" already exists when installing pgWatch

sql - Plesk 不显示所有数据库?

postgresql - 如何在postgresql中关闭分析器

sql - 带有索引的 Postgres 奇怪行为

ruby-on-rails - rails 4.1 通过 hstore 验证任意字段