Add column values created in PIVOT

Asked

Viewed 21 times

1

Well, in this query I have to list the products that went out for consumption in a certain period, and how much was consumed of each product. I have the Cód of the product, name, date of movement, quantity that was consumed and quantity in stock (sum of all stocks). But there are some considerations.. There are 2 types of product output, the output for patient that is (P) and output for sector that is (S), and this is in tp_mvto_stock. The (c) and (d) are returned, one of sector and another of patient.. The current stock is already the sum of the products in all stocks.. But I need to add the two outputs that are S and P and subtract by the sum of the returns that are C and D.. S+P-C+D, I tried to perform a pivot to list in columns to perform the sum and subtraction but without success, I cannot add the columns of the pivot in select to perform these operations. If you have a way or a better way, I’ll thank you.

Screenshot of the select output https://imgur.com/wsUYobj

SELECT

FROM

(

SELECT

TB1.CD_PRODUTO, TB1.DS_PRODUTO, TB1.TP_MVTO_ESTOQUE, TB1.QT_MOVIMENTACAO, TB1.DATA, TB1.ESTOQUE_ATUAL

FROM

(

SELECT

ITMVT.CD_PRODUTO, PROD.DS_PRODUTO, MVT.TP_MVTO_ESTOQUE, ITMVT.QT_MOVIMENTACAO, To_char(ITMVT.DH_MVTO_ESTOQUE,'MM') AS DATA, Sum(EP.QT_ESTOQUE_ATUAL) AS ESTOQUE_ATUAL

FROM

ITMVTO_ESTOQUE ITMVT, PROD PRODUCT MVTO_ESTOQUE MVT, EST_PRO EP

WHERE

ITMVT.DH_MVTO_ESTOQUE BETWEEN To_date ('19/12/2020 23:59:59','DD/MM/YYYY hh24:mi:ss') AND To_date ('26/12/2020 23:59:59','DD/MM/YYYY hh24:mi:ss') AND PROD.CD_PRODUTO = ITMVT.CD_PRODUTO AND PROD.CD_ESPECIE = 1 AND ITMVT.CD_MVTO_ESTOQUE = MVT.CD_MVTO_ESTOQUE AND MVT.TP_MVTO_ESTOQUE IN (’S','P','C',’D') AND EP.CD_PRODUTO = ITMVT.CD_PRODUTO

GROUP BY ITMVT.CD_PRODUTO, PROD.DS_PRODUTO, ITMVT.QT_MOVIMENTACAO, ITMVT.DH_MVTO_ESTOQUE, MVT.TP_MVTO_ESTOQUE

ORDER BY ITMVT.CD_PRODUTO

)TB1

ORDER BY TB1.CD_PRODUTO

)TB2

PIVOT (Sum(QT_MOVIMENTACAO) FOR TP_MVTO_ESTOQUE IN ('S','P','C','D'))
  
  ORDER BY 

  CD_PRODUTO
  • Try something like ... Sum( (CASE WHEN TP_MVTO_ESTOQUE IN (’S','P') THEN 1 ELSE -1 END) * EP.QT_ESTOQUE_ATUAL) ... the value stays with the signal

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.