I am trying to write an ORM query to join a table with itself after aggregation (Hence select_related
etc won't work). The corresponding SQL query is as below
select * from
transaction t
join
(
select account_id, sum(amount) as total_amount
from transaction
where amount > 0
group by account_id
) aggr
on t.account_id = aggr.account_id
where amount > 0.4 * total_amount;
So far no luck. I even tried the join_to/CustomJoin
from Django ORM. Joining subquery, but this didn' work.
Edit. Models are as below
class Account(models.Model):
currency = models.CharField(max_length=30)
...
class Transaction(models.Model):
account = models.ForeignKey(Account, db_constraint=False)
amount = models.DecimalField(max_digits=10, decimal_places=2)
booking_date = models.DateTimeField(db_index=True)
...