I am new to computer field and I am working on SQL. I am using multiple join queries in PostgreSql. I am trying to make inventory management system. I am having 3 tables as follow:
- inventory_limit_stock: id(int, PK), inventory_id (varchar), product_id(int), min_stock_limit(int)
- product_inventory: id(int, PK), inventory_id(int), product_id(int), in_stock(int)
- other_inventory: id(int, PK), product_id, A(int), B(int), C(int)
So I want to show the list of products that are less in stock than minimum limit set in Table 1. inventory_id in Table 1 contains value either in number or 'A','B','C'. If it;s number, it refers to Table 2 otherwise refers to Table 1. So for example if inventory_id of Table 1 contains value 2, it will check in Table 2 and get the in_stock value. While if it contains value 'A' than it refers to Table 3 with column A and the value in it will be taken.
I tried the following query but didn't worked for me.
SELECT ils.product_id as limit_prod, ils.inventory_id as limit_inv from inventory_limit_stock ils
left join product_inventory as pi on pi.product_id = ils.product_id
left join other_inventory oi on oi.product_id = ils.product_id
where (COALESCE(ils.min_stock_limit,0) > COALESCE(SUM(pi.in_stock), SUM(oi.limit_inv), 0)) group by ils.product_id, ils.inventory_id
I know there are too many mistakes in query, any help would be appreciated. Also sorry for this long elaboration of question, this is my first question here, hope you all understand. Thanks.
EDIT
Table 1 - inventory_limit_stock
id | product_id | inventory_id | min_stock_limit
1 | 121 | 5 | 25
2 | 052 | B | 27
3 | 8 | 13 | 11
4 | 121 | 13 | 35
Table 2 - product_inventory
id | product_id | inventory_id | in_stock
1 | 121 | 5 | 42
2 | 742 | 15 | 12
3 | 8 | 13 | 09
4 | 121 | 13 | 25
Table 3 - other_inventory
id | product_id | A | B | C
1 | 121 | 42 | 12 | 11
2 | 052 | 42 | 25 | 25
Result List (Should show list with products in_stock quantity < minimum limit)
product_id | inventory | minimum_stock_limit | in_stock_available
8 | 13 | 11 | 9
121 | 13 | 35 | 25
052 | B | 27 | 25