Select checking a condition

Asked

Viewed 70 times

2

I need to make a select where a condition is checked. Ex: If the value of a given field is < 0 assign the sum of that field to column "PerdaGerada" otherwise assign the column "LucroGerado".

Something as shown below:

SELECT TOP 10
       TBL.PRODUTO PRODUTO,
       COUNT(TBL.ID) AS QTD,

       SE TBL.VALORGANHO < = ENTAO SOMA DE VALOR GANHO VAI PRA COLUNA "PERDAGERADA"
       SE TBL.VALORGANHO > = ENTAO SOMA DE VALOR GANHO VAI PRA COLUNA "LUCROGERADO"


FROM TABELAVENDAS TBL
WHERE TBL.DATAEMISSAO BETWEEN '20150901' and '20150930' 
GROUP BY TBL.PRODUTO
ORDER BY 1 DESC
  • Tip: use CASE

  • I did so ... CASE WHEN(ACC.VALUATION < 0 SUM(ACC.VALUATION GAIN) AS PERDAGER ELSE SUM(ACC.VALUATION GAIN) AS ECONOMIAGER END , but it didn’t work out not

  • trial CASE WHEN x THEN y WHEN w THEN z END AS "alias" Unfortunately there is no way to make a dynamic alias, as far as I know.

  • I couldn’t do it this way ...

1 answer

4

To get this result you can use CASE

Example:

 SELECT TOP 10 TBL.PRODUTO , COUNT(TBL.ID) AS QTD , 
 SUM(CASE WHEN TBL.VALORGANHO <= 0 THEN TBL.VALORGANHO ELSE 0 END) AS PERDAGERADA , 
 SUM(CASE WHEN TBL.VALORGANHO >= 0 THEN TBL.VALORGANHO ELSE 0 END) AS lUCROGERADO FROM TABELAVENDAS TBL
    WHERE TBL.DATAEMISSAO BETWEEN '20150901' and '20150930' 
    GROUP BY TBL.PRODUTO
    ORDER BY 1 DESC
  • Diego, thank you so much !!! your answer was accurate !! Straight !!

  • @Alvarovieira I’m glad it worked out and helped !

Browser other questions tagged

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