根据其他列以不同方式对相同列进行求和 - Django ORM

时间:2016-07-04 13:09:22

标签: python mysql django

我有以下表格分配结构:

| employee | product | process | qty |
| Swati    | PROD1   | issue   |  60 |
| Rohit    | PROD1   | issue   |  30 |
| Rohit    | PROD2   | issue   |  40 |
| Swati    | PROD1   | receive |  40 |
| Swati    | PROD2   | issue   |  70 |

我希望每个员工的最终表格如此(例如employee = 'Swati'):

| product | sum_issued | sum_received
| PROD1   |         60 |           40 |
| PROD2   |         70 |            0 |

执行此操作的SQL查询是:

select product
     , sum(case when process='issue' then qty else 0 end) as sum_issued
     , sum(case when process='receive' then qty else 0 end) as sum_received 
  from assignment 
 where employee = 'Swati' 
 group 
    by product;

Django查询应该是什么,对应于这个结果?

1 个答案:

答案 0 :(得分:1)

我猜你的模特名称是'作业'。您可以使用以下查询

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()))
    )

如果您打印上述查询print result.query,则结果为

SELECT "product", SUM(CASE WHEN "process" = issue THEN "qty" ELSE 0 END) AS "sum_issued", SUM(CASE WHEN "process" = receive THEN "qty" ELSE 0 END) AS "sum_recived" FROM "assignment" WHERE "employee" = 'Swati' GROUP BY "product"