python - Sum same column in different ways depending on other column - Django ORM -
i have following table assignment structure:
| employee | product | process | qty | | swati | prod1 | issue | 60 | | rohit | prod1 | issue | 30 | | rohit | prod2 | issue | 40 | | swati | prod1 | receive | 40 | | swati | prod2 | issue | 70 |
i want final table each employee (say employee = 'swati'
):
| product | sum_issued | sum_received | prod1 | 60 | 40 | | prod2 | 70 | 0 |
the sql query is:
select product , sum(case when process='issue' qty else 0 end) sum_issued , sum(case when process='receive' qty else 0 end) sum_received assignment employee = 'swati' group product;
what should django query be, corresponding result?
i guess model name 'assignment'. can use below query
from django.db.models import case, value, when, sum, integerfield, count result = assignment.objects.filter(employee="swati").values('product').annotate( sum_issued=sum( case(when(process='issue', then='qty'), default=value(0), output_field=integerfield())), sum_recived=sum(case(when(process='receive', then='qty'), default=value(0), output_field=integerfield())) )
if print above query print result.query
, result is,
select "product", sum(case when "process" = issue "qty" else 0 end) "sum_issued", sum(case when "process" = receive "qty" else 0 end) "sum_recived" "assignment" "employee" = 'swati' group "product"
Comments
Post a Comment