Select checking for a condition

2

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

Something like 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
    
asked by anonymous 03.02.2016 / 13:19

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
    
03.02.2016 / 13:33