Skip to content

Instantly share code, notes, and snippets.

@JeffCohen
Last active August 29, 2015 14:07
Show Gist options
  • Save JeffCohen/d0727b130105929738ef to your computer and use it in GitHub Desktop.
Save JeffCohen/d0727b130105929738ef to your computer and use it in GitHub Desktop.
Product Queries
# Given these models:
#
# Customer
# - name: string
#
# Product
# - price: integer
#
# Order
# - customer_id: integer
# - shipping: integer
# - total: integer
#
# LineItem
# - order_id: integer
# - product_id: integer
# - price: integer
#
# and assume every model as a method called 'sample' which will
# return a random row from the database.
#
#
# Given:
# the_order = Order.sample
# the_product = Product.sample
#
# Can you write code to answer each question?
# 1. How many customers do we have?
# 2. What is the most expensive thing we sell?
# 3. What is the subtotal of the_order (the cost all items excluding shipping)?
# 4. On average, how much is spent on a typical order?
# 5. How many different products were purchased in the_order?
# 6. How many times has the_product ever been purchased?
# 7. How many orders contain the_product?
# 8. How many items in the_order cost more than $100?
# 9. How many people bought the_product?
# 10. What's the most popular product we sell?
@j55d
Copy link

j55d commented Oct 13, 2014

  1. Cusomer.count
  2. Product.where( price: Product.maximum('price'))
  3. the_order.total - the_order.shipping
  4. Order.average(:total)
  5. LineItem.where(order_id: the_order.id).count
  6. LineItem.where(product_id: the_product.id).count
  7. LineItem.where(product_id: the_product.id).pluck(:order_id).uniq.count
  8. LineItem.where(order_id: the_order.id).where("price > 100").count

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment