2016-12-30 29 views
0

我正在努力編寫一個聚合GROUP BY查詢與SQL Alchemy,該查詢返回聚合在一個表「更低」和一個聯合實體「更高」,這恰好是分組關鍵的,而不是返回聚集實體,如:SQLAlchemy group_by其中選擇不同於聚合目標

qry = session.query(PSU, func.count(PSU.id)).join(PSU).join(StockUnit).join(Part).group_by(Part) 

,但我想回到(第一部分,the_count),不(PSU,the_count)。寫作session.query(Part, func.count(...))查詢方式錯誤。

下面是使用SQL鍊金術語義我想查詢的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的基礎功能是什麼?

回答

0

使用select_from()控制的情況下,加入了「左」的一面,你需要它:

qry = session.query(Part, func.count(PSU.id)).\ 
    select_from(PSU).\ 
    join(StockUnit).\ 
    join(Part).\ 
    group_by(Part)