SQL Server – Performing SUM with Conditions

querysql server

I want to make SUM of a colummn according to various conditions. In this example for the column 'fac_saldo_tot' if value is greater than 500 add the column and group them down the column 'cli_razon_soc'

I have made this query but I do not perform the operation it only stores the higher values to 500 and otherwise it puts 0.
see image (red column)

    SELECT        cli_razon_soc, 
   CASE WHEN t .fac_saldo_tot > 500 THEN SUM(t .fac_saldo_tot) ELSE 0 END AS 'Mayor500'
FROM            cdc_vw_BuroCredito_Facturas95 AS t
GROUP BY cli_razon_soc, fac_saldo_tot
ORDER BY cli_razon_soc, 'Mayor500'

I appreciate the suggestions you can give me

enter image description here

This is the result I intend

enter image description here

Best Answer

SELECT        cli_razon_soc, 
SUM(CASE WHEN t .fac_saldo_tot > 500 THEN t .fac_saldo_tot ELSE 0 END) AS 'Mayor500'
FROM            cdc_vw_BuroCredito_Facturas95 AS t
GROUP BY cli_razon_soc, fac_saldo_tot
ORDER BY cli_razon_soc, 'Mayor500'

As the CASE operation is being applied to each row, checking the sum doesn't make sense logically. What we need to do for each row is check the value, if it's above 500 then sum it, else treat the value as 0.

The above code should accomplish this.