【问题标题】:Sum same column in different ways depending on other column - Django ORM根据其他列以不同方式对同一列求和 - Django ORM
【发布时间】:2016-07-04 13:09:22
【问题描述】:

我有如下表赋值结构:

| 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 查询应该是什么?

【问题讨论】:

    标签: python mysql django


    【解决方案1】:

    我猜您的模型名称是“Assignment”。您可以使用以下查询

    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"
    

    【讨论】:

    • 我试过写一些非常相似的东西,但查询总是给我一个由 output_field 引发的 FieldError。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-11-16
    • 2019-03-08
    • 2016-02-20
    • 2019-03-09
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多