Aggregate by another table after annotate

I have next annotate

qs.annotate(
    goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)),
)

Same goods_with_sales_percent=goods_with_sales / sum_sales * 100

I need get percent of goods_with_sales to sum of all goods__history__sales. I try it with Window but not happiness...

This is raw sql query:

SELECT  
  "wb_brand"."id", 
  "wb_brand"."name", 
  COUNT("wb_good"."id") FILTER (
    WHERE 
      "wb_stockshistory"."sales" > 0
  ) AS "goods_with_sales" 
FROM 
  "wb_brand" 
  LEFT OUTER JOIN "wb_good" ON (
    "wb_brand"."id" = "wb_good"."brand_id"
  ) 
  LEFT OUTER JOIN "wb_stockshistory" ON (
    "wb_good"."id" = "wb_stockshistory"."good_id"
  ) 
GROUP BY 
  "wb_brand"."id"

Also I tried this with CTE, but not happiness also.

How can I solve it with Django ORM (prefer) or with SQL ? P.S. Also must be CASE/WHEN condition for divisizon by zero if sum_sales == 0.

Back to Top