Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Komplexe SQL-Abfrage zum Inventar mehrerer Tabellen

Verwenden Sie die folgende Abfrage

select Inventory.ItemID, Inventory.ItemName, 
sum(case when Inventory.TransactionDate<currentdate() then Inventory.Quantity else 0 end)+sum(case when ConsumedItems.TransactionDate<currentdate() then ConsumedItems.Quantity else 0 end)-sum(case when DamagedItems.TransactionDate<currentdate() then DamagedItems.Quantity else 0 end) as 'PrevBalance',
sum(case when DamagedItems.TransactionDate=currentdate() then DamagedItems.Quantity else 0 end) as 'DamagedToday',
sum(case when ConsumedItems.TransactionDate=currentdate() then ConsumedItems.Quantity else 0 end) as 'ConsumedToday', 
sum(case when ConsumedItems.TransactionDate=currentdate() then ConsumedItems.Quantity else 0 end)+sum(case when DamagedItems.TransactionDate=currentdate() then DamagedItems.Quantity else 0 end)+sum(case when Inventory.TransactionDate=currentdate() then Inventory.Quantity else 0 end) as 'DeliveredToday' 
from Inventory 
join ConsumedItems on ConsumedItems.ID = Inventory.ID 
join DamagedItems on DamagedItems.ID = Inventory.ID
group by  Inventory.ItemID, Inventory.ItemName