2015-09-11 43 views
4

我安裝我的數據庫是這樣的:跟蹤應用程序中的產品銷售並選擇最暢銷的最佳方式是什麼?

產品:

# id    :integer   not null, primary key 
# code   :string 
# name   :string 
# category_id :integer 
... 

訂單項目:

# id    :integer   not null, primary key 
# order_id  :integer 
# product_id  :integer 
# color_id  :integer 
# qty    :integer   default("0") 
# price   :money 
... 

訂單:

# id     :integer 
# state    :string 
# placed_on   :datetime 
... 

現在這種設置使它真正難我挑選best selling products in each week from each category。我怎樣才能解決這個問題?另一個數據庫來跟蹤銷售情況?請幫忙。

+0

從每個類別**每週定義**暢銷產品的條件是什麼? – Pavan

+0

@Pavan我需要根據銷售數量選擇最暢銷的產品。必須通過Orderitem的數量獲得銷售數量 – THpubs

+0

我對此進行了演示:https://www.youtube.com/watch?v=BVzSMhaucUY – drhenner

回答

5

你基本需要的是加入categories,products,order_itemsorders表。

聯袂可以用下面的代碼來完成:在此基礎上,你可以在日期間隔過濾

rel = Category.joins(products: [order_items: :order]) 
#=> SELECT "categories".* FROM "categories" INNER JOIN "products" ON "products"."category_id" = "categories"."id" INNER JOIN "order_items" ON "order_items"."product_id" = "products"."id" INNER JOIN "orders" ON "orders"."id" = "order_items"."order_id" 

假設我們已經有d1d2值,它定義的時間間隔的開始和結束時,我們感興趣的是:

rel = rel.where('orders.placed_on >= ? AND orders.placed_on <= ?', d1, d2) 

現在,你可以在字段彙總:

result = rel.select('categories.id, categories.name, SUM(order_items.qty) as qty, SUM(order_items.qty * order_items.price) as total') 
    .group('categories.id, categories.name') 
sample = result.first 
sample.id # => 1 
sample.name # => "Category 1" 
sample.qty # => 100.0 
sample.total # => 500.0 
0

這看起來就像一個簡單的數據庫查詢給我。以下應該是實現它的簡單而直接的步驟。

  • 加入三個表
  • 過濾它通過date
  • 集團通過product_id
  • 總結了qty
  • 而且,排序彙總值。

我對獲取日期的方法沒有信心。請在下面的查詢中填寫你自己。

SELECT P.id, P.name, P.category_id, SUM(qty) as LastWeekSales 
FROM Product as P INNER JOIN Order Items as OI 
        ON P.id = OI.product_id 
    INNER JOIN Order as O 
        ON O.id = OI.order_id 
WHERE O.placed_on <= GetTodaysDate() AND O.placed_on > GetOneWeekBacksDate() 
GROUPBY P.category_id 
ORDERBY WeekSales 

所有你需要做的是,在的Ruby-on-軌道準備這個查詢。我會這樣做,但我不知道任何關於ruby​​-on-rails

0

+1在模型中處理此問題。如果你在此期間需要它,這裏有一些工作的入門代碼。哈,今天晚上我正在練習操縱哈希以防萬一你說不出來。

添加至訂單模型:

def self.last_week 
    Order.where(" created_at >= ? ", 1.week.ago.utc) 
end 

添加到任何控制器:

@qty_hash = category = Hash.new 0; 
@output_hash = Hash.new { |hash, key| hash[key] = {} } 

@recently_ordered_items = OrderItem.find_all_by_order_id(Order.last_week) 
@recently_ordered_items.each { |i| @qty_hash[i.product_id] += i.qty } 
@recent_products=Product.find_all_by_id(@qty_hash.keys) 

@qty_hash.each do |key, value| 
    @recent_products.each { |i| category = i.category_id if i.id == key } 
    @output_hash[category] = @output_hash[category].merge(@qty_hash.slice(key)) 
end 

@output_hash是輸出,是在格式: {1 => {3 => 9} ,2 => {4 => 8,6 => 5,7 => 4}}

在這種情況下,類別是1和2,產品id是3(9 sold),4(8 sold), 6(已售出5件)和7件(已售出4件)

經過測試和工作。祝你好運。

相關問題