回答

12

是的,当然可以。一个GROUP BY子句是一个非常通用的工具,所以你可以用任何你想要的表达式进行分组。因此,给定的数据是这样的:

=> select * from with_hstore order by id; 
id |   h   
----+-------------------- 
    1 | "a"=>"6" 
    2 | "a"=>"2" 
    3 | "b"=>"1" 
    4 | "a"=>"b" 
    5 | "x"=>"z", "y"=>"6" 
    6 | "a"=>NULL 

您可以通过使用h -> key键的值组:

=> select h -> 'a', count(*) from with_hstore group by h -> 'a'; 
?column? | count 
----------+------- 
      |  3 
2  |  1 
6  |  1 
b  |  1 

注意,一个缺少键和空值会在这里结束出来一样。你甚至可以通过一键存在使用组exist

=> select exist(h, 'a'), count(*) from with_hstore group by exist(h, 'a'); 
exist | count 
-------+------- 
f  |  2 
t  |  4 

你不会想group by (h -> 'a') is not null虽然你可以有NULL值,该标准将不能没有一个明确的NULL和hstore区分关键问题;当然,这可能是你想要的,所以也许你想按(h -> 'a') is not null分组。

的ActiveRecord将让你按什么数据库可以通过传送组的情况作为一个SQL片段处理:

Model.group("h -> 'a'")... 
Model.group("exist(h, 'a')")... 
... 
相关问题