Sum Sql Server with condition

0

I have the following query:

select distinct GETDATE() as Fecha_Actual, f353_fecha_vcto, DATEDIFF(day, 
f353_fecha_vcto, GETDATE()) AS Dias_Vencidos, 
f353_consec_docto_cruce, f353_total_db, f353_total_cr, f353_total_db - 
f353_total_cr AS Valores
from t350_co_docto_contable
INNER JOIN t200_mm_terceros ON 
t200_mm_terceros.f200_rowid=t350_co_docto_contable.f350_rowid_tercero
INNER JOIN t353_co_saldo_abierto ON 
t353_co_saldo_abierto.f353_rowid_docto=t350_co_docto_contable.f350_rowid
INNER JOIN t354_co_mov_saldo_abierto ON 
t354_co_mov_saldo_abierto.f354_rowid_docto
=t350_co_docto_contable.f350_rowid
INNER JOIN t351_co_mov_docto ON 
t351_co_mov_docto.f351_rowid_docto=t350_co_docto_contable.f350_rowid
WHERE f350_id_tipo_docto LIKE 'FV%' AND f200_nit = '1035877400' AND 
f350_id_periodo >= '201807' AND f351_id_periodo >= '201807'
AND f353_total_db - f353_total_cr <> 0 ORDER BY Dias_Vencidos

These are the results of the query:

What I need to do is the following: create in the query a column Vencidos and add the figures of the field Valores with the condition that the field Dias_Vencidos is greater than 0

If the value of Dias_Vencidos is less than or equal to 0, you will do the same but not in the column Vencidos if not in a column Corriente

    
asked by The_pacha 04.09.2018 в 18:29
source

1 answer

5

What you need for your problem is to apply a CASE as follows:

SELECT t.campo1, 
CASE WHEN t.Dias_Vencidos > 0 THEN SUM(t.Valores) ELSE 0 END 'Vencidos',
CASE WHEN t.Dias_Vencidos < 0 THEN SUM(t.Valores) ELSE 0 END 'Corriente'
FROM tuTabla t
GROUP BY t.campo1, t.Dias_Vencidos 

You tell us

    
answered by 04.09.2018 / 18:48
source