Skip to content

Instantly share code, notes, and snippets.

@PlaidShirtPat
Last active August 29, 2015 14:10
Show Gist options
  • Save PlaidShirtPat/f8f37f0bd8d6524cb90c to your computer and use it in GitHub Desktop.
Save PlaidShirtPat/f8f37f0bd8d6524cb90c to your computer and use it in GitHub Desktop.
sql issue
Two tables:
Categories
:id,
:name
Instances
:id,
:category_id,
:another_id,
:quantity
Category.
joins('LEFT JOIN "instances" ON "instances"."category_id" = "categories"."id"').
select("SUM(instances.quantity) as quantity, ").
group("instances.category_id")
But I need to filter by :another_id and I have no idea how to without removing some categories without any instances with that id
@PlaidShirtPat
Copy link
Author

quantity_query =  "(SELECT SUM(quantity) as quantity FROM instances WHERE instances.category_id= categories.id AND instances.another_id = 5) as quantity"

items = Category.
      select("categories.*, " +  quantity_query)

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