简体   繁体   中英

Query to aggregate across multiple tables

I'm new to SQL, and I'm trying to create a database to manage a small inventory. This is the structure of the db:

DatabaseStructure

I need to create a query that returns the total inventory per material. So, the first step would be to look up for all the batches associated with the material. Second, look up for all the movements associated with each batch. Then, sum the quantity associated with each movement, but depending on the movement type (If it is a good receipt is addition (+), but if it is an inventory withdrawal is subtraction (-)).

Here is an example of the tables with sample data and the desired result.

Table Material

MaterialID MaterialDescription
1 Bottle
2 Box

Table Batch

BatchID MaterialID VendorMaterial VendorBatch ExpirationDate
1000 1 2096027 00123456 12/12/2025
1001 1 2096027 00987654 11/11/2026
1002 2 102400 202400E 10/10/2023

Table Movement

MovementID BatchID MovementType Quantity CreatedBy CreatedOnDate
1 1000 Good receipt 100 user1@email.com 4/10/2022
2 1000 Inventory withdrawal 20 user2@email.com 4/15/2022
3 1000 Inventory withdrawal 25 user3@email.com 4/17/2022
4 1001 Good receipt 100 user1@email.com 4/20/2022
5 1001 Inventory withdrawal 10 user4@email.com 4/26/2022
6 1002 Good receipt 50 user1@email.com 2/26/2022

Expected query result - total inventory per material:

MaterialDescription TotalInventory
Bottle 145
Box 50

TotalInventory calculation: for Bottle there are two good receipts movements of 100 and three withdrawals of 20, 25 and 10. So, total inventory will be (100+100)-(20+25+10)=145.

Thanks for your help!

select
    mat.MaterialDescription,
    sum(
        case mov.MovementType
            when 'Good receipt' then 1
            when 'Inventory withdrawal' then -1
            else 0 /* don't know what to do for other MovementTypes */
        end * mov.Quantity
    ) as TotalInventory
from
    Material as mat
    left join Batch as bat on bat.MaterialID = mat.MaterialID
    left join Movement as mov on mov.BatchID = bat.BatchID
group by
    mat.MaterialDescription
;

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