我正在尝试制定一个获取两个聚合(avg)列的查询。没有分组依据,我希望在整个结果集中计算汇总。
我想为每个满足特定条件的用户计算最新结果中几个属性的平均值。
以下原始sql可以正常工作:
SELECT AVG(r.points), AVG(r.maxforanswered)
FROM "result" r,
"user" u
WHERE
u.birth_date BETWEEN CURRENT_DATE - ($highage * 365)
AND CURRENT_DATE - ($lowage * 365)
AND u.gender = $gender
AND r.user = u.id
AND r.time_generated = (SELECT MAX(r2.time_generated)
FROM "result" r2
WHERE r2.user = u.id)
我尝试了多种配方。当我阅读文档时,它应该起作用:
select((avg(r.points), avg(r.maxforanswered))
for r in Result
for u in User
if r.user == u
and u.gender == gender
and between(u.birth_date, dminus, dplus)
and r.time_generated ==
max(r2.time_generated for r2 in Result if r2.user == u))
文档说聚合列将不包含在GROUP BY中。但是我收到一条错误消息,指出这是不对的:
pony.orm.dbapiprovider.ProgrammingError:聚合函数不正确 在第11行的GROUP BY中允许:GROUP BY AVG(“ r”。“ points”), AVG(“ r”。“ maxforanswered”)
我想知道什么是pony语法(如果有)直接实现SQL中容易做到的事情。