如何访问Postgres hstore字段中的数据并从Active Record中求和

时间:2015-10-12 02:46:57

标签: sql postgresql ruby-on-rails-4 activerecord hstore

我有一个Postgres 9.3.5 DB,其中有一个名为order_items的表。数据的布局就像这样。

root.after(1000, navigationmain, "PLACEHOLDER")

我想要了解的是每个product_sku在表格中出现的频率以及总数"金额"对于那个产品。

如果我运行以下内容,我会得到这个结果。

 id | product_sku(character var) | qty_ordered(integer) | item_price(hstore)
1   | 9AYSNL                     | 1                    |"Amount"=>"5.99", "CurrencyCode"=>"USD"
2   | 9AYSNL                     | 1                    |"Amount"=>"5.99", "CurrencyCode"=>"USD"
3   | 9AYSNL                     | 2                    |"Amount"=>"11.98", "CurrencyCode"=>"USD"
4   | 9AYSNL                     | 1                    |"Amount"=>"5.99", "CurrencyCode"=>"USD"
5   | EZAY1D                     | 1                    |"Amount"=>"21.98", "CurrencyCode"=>"USD"

我想以某种方式返回类似下面的内容(total_orders是product_sku在表中的次数而不是有序的数量)。我想以total_orders返回前20名。

products =  OrderItem.where('quantity_ordered > 0').group(:product_sku).count

{"9AYSNL"=>4,
"EZAY1D"=>1}

1 个答案:

答案 0 :(得分:2)

要获得结果:

SELECT product_sku
     , count(*) AS total_orders
     , sum((item_price->'Amount')::numeric) AS total_order_amount
FROM   orderitem
WHERE  qty_ordered > 0
GROUP  BY product_sku
ORDER  BY count(*) DESC
LIMIT  20;  -- get only top 20

将结果显示为JSON数组,如下所示:

SELECT json_agg(t)
FROM  (
   SELECT product_sku
        , count(*) AS total_orders
        , sum((item_price->'Amount')::numeric) AS total_order_amount
   FROM   orderitem
   WHERE  qty_ordered > 0
   GROUP  BY product_sku
   ORDER  BY count(*) DESC
   LIMIT  20
   ) t;

SQL fiddle.