Complex nested aggregations to get order totals - part 2

≯℡__Kan透↙ 提交于 2020-05-17 06:31:04

问题


Follow-up to this answered question:

Complex nested aggregations to get order totals

After getting it answered I realized that it would be much easier if I start of with:

Budget.find(2).cbs_items.order('cbs_items.name ASC').select(:id, :name)
  Budget Load (0.3ms)  SELECT  "budgets".* FROM "budgets" WHERE "budgets"."company_id" = 9 AND "budgets"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  CbsItem Load (1.6ms)  SELECT "cbs_items"."id", "cbs_items"."name" FROM "cbs_items" INNER JOIN "cost_breakdown_structures" ON "cbs_items"."cost_breakdown_structure_id" = "cost_breakdown_structures"."id" AND "cbs_items"."company_id" = "cost_breakdown_structures"."company_id" WHERE "cost_breakdown_structures"."company_id" = 9 AND "cbs_items"."company_id" = 9 AND "cost_breakdown_structures"."id" = $1 ORDER BY cbs_items.name ASC  [["id", 2]]
=> [#<CbsItem:0x00007f7f4605c3b0 id: 9, name: "100">, #<CbsItem:0x00007f7f460569b0 id: 10, name: "200">, #<CbsItem:0x00007f7f4604f908 id: 11, name: "300">]

Ignore the company_id references - part of my multi-tenant code. In my view I get the list of cbs_items all sorted. Now I want to layer on the answer from the previous question.

I revised the other Fiddle answer to get the results I am looking for:

https://dbfiddle.uk/?rdbms=postgres_11&fiddle=e521b78ff8e8d4e7d9bba0eee37d5dd5

I am not sure how to pose the actual question here.

I can work with the result from this as raw SQL but in a Rails app it's less than ideal. I am sure I can this work but I think it has to start with SELECT "cbs_items"."id"... FROM "cbs_items"... and add the subqueries onto that. Rails Active Record seems to support subqueries.

So to start perhaps: How would I modify the above Fiddle to start with?:

SELECT ... FROM "cbs_items" ...

In this answer:

Rails raw SQL example

I could use CbsItem.find_by_sql(... to convert this to a normal Rails active record call.

来源:https://stackoverflow.com/questions/61706844/complex-nested-aggregations-to-get-order-totals-part-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!