具有多个筛选聚合的SQLAlchemy查询

时间:2018-07-09 11:00:27

标签: python mysql sqlalchemy

说我们有一个mysql数据透视查询(取自pivto表问题的答案  MySQL pivot table)与内部联接。

select projects.org,  SUM(ivt_incidents.severity = 'SEV3') as 
sev3_count, 
SUM(ivt_incidents.severity = 'SEV2') as sev2_count, 
SUM(ivt_incidents.severity = 'SEV1') as sev1_count, 
SUM(ivt_incidents.severity = 'SEV0') as sev0_count, 
SUM(ivt_incidents.severity like '%SEV%') as total_count  from 
ivt_incidents inner join projects on ivt_incidents.jira_key = 
projects.jira_key group by projects.org order by total_count;

在构建sqlalchemy查询时寻求帮助:

response = db.session.query(
        func.sum(Incidents.severity).filter(Incidents.severity == 'SEV3'),
        Projects.org).\
    join(Projects, Projects.jira_key == Incidents.jira_key).\
    group_by(Projects.org)

如果我运行它,它将接受查询,但是如果我调用

response.all()
  

ProgrammingError:(mysql.connector.errors.ProgrammingError)1064(42000):SQL语法有错误;请在第1行[SQL:u'SELECT sum(ivt_incidents。)中检查与您的MySQL服务器版本相对应的手册,以在'(WHERE ivt_incidents.severity ='SEV3')AS anon_1,projects.org AS projects_org'附近使用正确的语法。严重性)(FILTER(WHERE ivt_incidents.severity =%(severity_1)s)AS匿名_1,projects.org AS projects_org \ nFROM ivt_incidents INNER JOIN项目位于projects.jira_key = ivt_incidents.jira_key GROUP BY projects.org'] [参数:{u'严重性_1':'SEV3'}](此错误的背景位于:http://sqlalche.me/e/f405

1 个答案:

答案 0 :(得分:0)

MySQL不支持您尝试在func.sum(...).filter(...)中使用的SQL标准aggregate FILTER clause中的✝️,该标准已编译为

SUM(...) FILTER (WHERE ...)

查看原始查询,您应该将谓词表达式作为SUM的参数传递:

response = db.session.query(
        func.sum(Incidents.severity == 'SEV3'),
        Projects.org).\
    join(Projects, Projects.jira_key == Incidents.jira_key).\
    group_by(Projects.org)

仅在调用Query.all()之后才得到错误的原因是,查询实际上是在数据库中发出的。在此之前,您已经构建了Query对象。

✝️:有一个plugin通过重写查询为MySQL添加了FILTER支持。