简体   繁体   中英

How to convert SQL statement into correct SQLAlchemy expression

I have an SQL statement to calculate the amount of stock I have on different items. Therefore I sum up all items delivered and subtract all items sold. The SQL statement that gives me the correct result is the following:

SELECT     Item.id,
    Item.description,
    deliver.del_amount,
    sell.sell_amount ,
    deliver.del_amount - sell.sell_amount as stock
from item
join (
    select Deliveryitem.Item_id as del_id,
    sum(DeliveryItem.amount) as del_amount
    from  Deliveryitem group by DeliveryItem.item_id

) deliver on deliver.del_id = item.id
 join (
    SELECT LineItem.Item_id as sell_id,
    sum(LineItem.amount) as sell_amount
    from  LineItem  group by LineItem.item_id
) sell on sell.sell_id=item.id

Now I need to convert this into an equivalent SQLAlchemy statement. I have no idea how I express the two joins in combination with the deliver and sell labels correctly. Could someone please help me out here?

The beauty of SQLAlchemy is that when you start getting into complex queries that are not easy to express in SQLAlchemy expression syntax you can use straight SQL and still populate the results into your ORM classes.

you can do something along the lines of

Session.query(Item, deliver, sell, stock).from_statement("""
SELECT     Item.id,
    Item.description,
    deliver.del_amount,
    sell.sell_amount ,
    deliver.del_amount - sell.sell_amount as stock
from item
join (
    select Deliveryitem.Item_id as del_id,
    sum(DeliveryItem.amount) as del_amount
    from  Deliveryitem group by DeliveryItem.item_id

) deliver on deliver.del_id = item.id
 join (
    SELECT LineItem.Item_id as sell_id,
    sum(LineItem.amount) as sell_amount
    from  LineItem  group by LineItem.item_id
) sell on sell.sell_id=item.id
""")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM