2011-10-24 7 views
0

を呼び出し、私は次のフィールドがあり、販売、という名前のテーブルを持っています私が望むようにデータを表示する。 Googleの視覚化の統合は問題ではありません。問題は、私がgroup()機能を得ることができないか、またはselect()機能を私がしたいと思うことができないことです。レールを選択し、グループのカスタムSQLは

私はそのグループが私の望むものではないと思っていますが、基本的には、製品ごとの売上合計をpayment_methodでしたいと考えています。

私のオリジナルのアイデアは、それが

.select("SUM(quantity) as total_sold", :product_id).group(:payment_method) 

のようになります。しかし、それは本当に私は、製品によってそれらを並べ替える助けにはならないということでした。どのようなデータを表示したいのですか:

CASH SALES: 
    Product A: 103 sales 
    Product B: 32 sales 
    Product C: 87 sales 
CREDITCARD SALES: 
    Product A: 23 sales 
    Product B: 43 sales 
    Product C: 12 sales 
DONATION SALES: 
    Product A: # sales 
    Product B: 43 sales 
    Product C: 12 sales 

助けていただければ幸いです。

答えて

0
.select("SUM(quantity) as total_sold", :product_id).group(:payment_method, :product_id) 

ここでは、最初に、支払い方法と商品IDで結果セットをグループ化します。

+0

私はエラーを取得しておく:「引数エラー:

.select("SUM(quantity) as total_sold, payment_method, product_id").group(:payment_method, :product_id) 

がレールコンソールを使用してテストされています。?引数の数が間違って(1 2)をquery_methods.rbから任意の考えを – jyanks

+0

I selectメソッドの2つのパラメータを渡すことはできないと思いますので、.select( "SUM(quantity)as totla_sold、product_id")としてください – nkm

+0

product_idと:product_idを使って試してみました。数量と同じもの:数量 – jyanks

0

すべての列を1つの文字列の中に選択したままにします。生成されたSQLは「そのまま」使用します。文字列を閉じ、2番目のパラメータをシンボル:product_idとして選択する必要はありません。 selectでgroup byのすべての列を追加することも重要です。 .order("payment_method, product_id")も検討してください。

Product.select("product_line_id, public_product_id pp_id, count(product_id) num_products") .group("product_line_id, public_product_id").map{|p| "Public Prod Id: #{p.pp_id} has #{p.num_products} products " } 

Product Load (0.2ms) SELECT public_product_id pp_id, count(product_id) num_products FROM products GROUP BY products . public_product_id => [ "Public Prod Id: 5 has 1 products ", "Public Prod Id: 6 has 2 products ", "Public Prod Id: 8 has 1 products ", ... ]

関連する問題