【发布时间】:2017-05-14 19:22:51
【问题描述】:
我正在努力使用 SQL Alchemy 编写一个聚合 GROUP BY 查询,该查询返回对“较低”表和一个恰好是分组键的连接实体“较高”进行聚合的结果,而不是返回聚合实体,例如:
qry = session.query(PSU, func.count(PSU.id)).join(PSU).join(StockUnit).join(Part).group_by(Part)
但我想返回 (Part, the_count),而不是 (PSU, the_count)。写session.query(Part, func.count(...)) 查询错误。
这是我想要使用 SQL Alchemy 语义查询的 SQL:
select
psu.package_id,
p.*, -- the joined entity
count(psu.*) -- the aggregate
from packaged_stock_unit psu
inner join stock_unit su
on su.id = psu.stock_unit_id
inner join part p
on p.id = su.part_id
where
psu.some_value = 1
and psu.package_id = 1
group by psu.package_id, p.sku;
也许这可以通过 SQLAlchemy 基本函数实现?
【问题讨论】:
标签: python sql postgresql group-by sqlalchemy