如何使用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;
答案 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())