Can peewee nest SELECT queries such that the outer query selects on an aggregate of the inner query?

佐手、 提交于 2019-12-04 16:31:39

I posted the same question on the peewee-orm Google group. Charles Leifer responded promptly with both an answer and new commits to the peewee master. So although I'm answering my own question, obviously all credit goes to him.

You can see that thread here: https://groups.google.com/forum/#!topic/peewee-orm/FSHhd9lZvUE

But here's the essential part, which I've copied from Charles' response to my post:

I've added a couple commits to master which should make your queries possible (https://github.com/coleifer/peewee/commit/22ce07c43cbf3c7cf871326fc22177cc1e5f8345).

Here is the syntax,roughly, for your first example:

SELECT ev_tix, count(1) AS ev_tix_n FROM 
(SELECT count(1) AS ev_tix FROM ticket GROUP BY event_id)
GROUP BY ev_tix
ev_tix = SQL('ev_tix')  # the name of the alias.
(Ticket
 .select(ev_tix, fn.count(ev_tix).alias('ev_tix_n'))
 .from_(
     Ticket.select(fn.count(Ticket.id).alias('ev_tix')).group_by(Ticket.event))
.group_by(ev_tix))

This yields the following SQL:

SELECT ev_tix, count(ev_tix) AS ev_tix_n FROM (SELECT Count(t2."id") 
AS ev_tix FROM "ticket" AS t2 GROUP BY t2."event_id")
GROUP BY ev_tix
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!