GROUP BY应该放在哪里?

问题描述

我正在浏览代码库,并且遇到了一些原始sql,如下所示


    SELECT count(1) AS "n","forms_newspaperperson"."sex","forms_newspapersheet"."topic" 
    FROM "forms_newspaperperson" 
    INNER JOIN "forms_newspapersheet" ON ("forms_newspaperperson"."newspaper_sheet_id" = "forms_newspapersheet"."id"),"reports_weights" 
    WHERE ("forms_newspaperperson"."deleted" = %s 
    AND "forms_newspapersheet"."country" IN (%s) 
    AND "forms_newspaperperson"."sex" IN (%s,%s) 
    AND (reports_weights.country = forms_newspapersheet.country) 
    AND (reports_weights.media_type = 'Print'))`

这会引发以下错误

django.db.utils.ProgrammingError: column "forms_newspaperperson.sex" must appear in the GROUP BY clause or be used in an aggregate function
web_1  | LINE 1: SELECT count(1) AS "n","form...

关于将GROUP BY放在哪里的任何建议?

解决方法

您有一个汇总查询。因此,您需要一个group by

SELECT count(1) AS "n",npp."sex",nps."topic"
FROM "forms_newspaperperson" npp INNER JOIN
     "forms_newspapersheet" nps
     ON npp."newspaper_sheet_id" = nps."id" CROSS JOIN
     "reports_weights" w
     ON w.country = npp.country
WHERE npp."deleted" = %s AND nps."country" IN (%s) AND
      npp."sex" IN (%s,%s) AND w.media_type = 'Print'
GROUP BY npp."sex",nps."topic";

还请注意,我修复了FROM子句,以删除逗号(过时的逗号),并用正确,显式,标准,可读的JOIN语法替换了它