如何形成复杂的mysql查询已离开外部联接,使用SQLAlchemy聚合数据与组?

时间:2015-06-19 15:28:13

标签: mysql sqlalchemy flask-sqlalchemy

如何使用SQLAlchemy编写以下查询?

baz_id

这是我最后写的:

SELECT i.itemid, sum(i.quantitysold) total_quantity_sold, max(t.createdAt) last_sale_time
FROM ItemList i LEFT OUTER JOIN ItemTransactions t ON i.itemid = t.itemid
WHERE i.active = 'y'
GROUP BY i.itemid
ORDER BY total_quantity_sold asc;

1 个答案:

答案 0 :(得分:1)

from sqlalchemy.sql import func

query = ItemList.query.with_entities(ItemList.itemid)
query = query.outerjoin(ItemTransactions, ItemTransactions.itemid == ItemList.itemid)
query = query.add_columns(func.sum(ItemList.quantitySold).label('total_quantity_sold'))
query = query.add_columns(func.max(ItemTransactions.createdAt).label('last_sale_time'))
query = query.filter(ItemList.active == "y")
query = query.group_by(ItemList.itemid)
query = query.order_by(func.sum(ItemList.quantitySold).asc())