Django中的多个group by和join语句

时间:2017-09-27 17:37:08

标签: python mysql django

我在原始SQL中有以下查询,我想使用Django ORM重写它。

 SELECT
      id,
      username,
      COALESCE(total, 0) as total,
      COALESCE(sum1, 0) as sum1,
      COALESCE(sum2, 0) as sum2,
      COALESCE(sum3, 0) as sum3,
      COALESCE(sum4, 0) as sum4,
      COALESCE(sum5, 0) as sum5
    FROM
      (SELECT
         s_id,
         SUM(am) AS total
       FROM S
       GROUP BY s_id
       ORDER BY total) AS total

      LEFT OUTER JOIN (

                        SELECT
                          s_id,
                          SUM(am) AS sum1
                        FROM submitted
                        WHERE category = ‘m’
                        GROUP BY s_id
                      ) AS sum1 USING (s_id)

      LEFT OUTER JOIN (

                        SELECT
                          s_id,
                          SUM(am) AS sum2
                        FROM submitted
                        WHERE category = ’s’
                        GROUP BY s_id
                      ) AS sum2 USING (s_id)

我可以使用以下方法在Django中按表格分组:

S.objects.values('s_id').annotate(total=Sum('am'))

问题是我需要以某种方式将此结果与表S连接,然后一次又一次。有没有办法比使用Django ORM更好?

0 个答案:

没有答案