I have a product registration table (about 5,000 items) called Tab_Product, and in this table I have the following columns: COD_ Product (Product code) and type_product (C: purchased, P: Produced). Query needs to basically bring this table and insert an additional column named Cost_product, with the unit cost of each product, calculated as follows:
When the product is type C (purchased), the cost of it It will be searched at a table that has the cost of all purchased items, called Tab_Cust. This part is quiet, this table has the following columns: cod_product (product code) and value_costo_compra.
When the item is type P (produced), its cost will be the sum of the cost of children, calculated from a good table (Bill of Materials) called Tab_Bom, and is in that part I screwed up. This table has the following columns: cod_produto_pai, cod_produto_filho and qtd_necessaria.
If a product of Tab_Product is a produced item and is formed, for example, by 10 different components, in Tab_Bom there will be 10 records relating to this item. The 10 records will have the same cod_product in the COD_PRODUTO_PAI column, and each will have a different cod_produto and qtd_necess.
The cost of a product produced from Tab_Product will then be the sum of the cost of all your children. When a child is a purchased item, just multiply the QTD_BOM's QTD_BOM for the value_costo_cupra from the tab_cost table. When a child is produced, I would have to multiply the amount of it by the sum of the cost of their own children, that is, grandchildren of the first product in question.
In the examples I found in the forum, I saw the staff using Connect, but the good of the examples generally had the hierarchical level of the items in question, but in my good table there is no indication of the level, I believe that by the fact that an item is used as a component of various products.
was developing something in this line of reasoning, but I believe it is wrong:
SELECT T1.COD_PRODUTO,
CASE WHEN T1.TIPO_ITEM = 'C'
THEN T2.VALOR_CUSTO_COMPRA
ELSE SELECT SUM(CASE WHEN(T3.COD_PRODUTO_PAI = T1.COD_PRODUTO AND T1.TIPO_ITEM = 'C')
THEN T3.QTD_NECESSARIA * T4.VALOR_CUSTO_COMPRA
ELSE T3.QTD_NECESSARIA * SELECT...??? (LOOPING PARA CADA VEZ QUE ELE ENCONTRA UM FILHO TIPO 'P')
FROM TAB_BOM T3
INNER JOIN TAB_CUSTO T4 ON (T4.COD_PRODUTO = T3.COD_PRODUTO_FILHO)
FROM TAB_PRODUTO T1
INNER JOIN TAB_CUSTO T2 ON (T2.COD_PRODUTO = T1.COD_PRODUTO)
If someone can help, I will be very grateful.