How to generate multiple columns in a query from just one column?

4

I need a Query that returns 2 columns added (input and output) from the "accounting" column of the "tbl_sef" table. The value of the "accounting" column will be in the "input" column when the "cfop" column is less than 5000. And it will be in the "output" column when the cfop column value is greater than or equal to 5000.

tbl_sef:

Theidealreturnwouldbe:

I tried in many ways and I could not!

    
asked by anonymous 16.08.2017 / 18:47

2 answers

4

Use the SUM aggregation function together with the CASE structure:

SELECT inscricao,
       SUM(CASE WHEN cfop < 5000 THEN contabil ELSE 0 END) AS entrada,
       SUM(CASE WHEN cfop >= 5000 THEN contabil ELSE 0 END) AS saida
  FROM tbl_sef
 GROUP BY inscricao
    
16.08.2017 / 18:54
1

You can use CASE to septate with SUM to add:

select
    tbl_sef.incricao,
    SUM(case
        when tbl_sef.cfop < 5000 then tbl_sef.contabil
    end case) as Entrada,
    SUM(case
        when tbl_sef.cfop >= 5000 then tbl_sef.contabil
    end case) as Saida
from
    tbl_sef
    
16.08.2017 / 18:59