Search code examples
sqlsql-serversum

SQL query should return percentage but returns error


I have the following lines of code:

ROUND((((SUM(VALOR_2)) - SQLTMP.VALOR_1) / SQLTMP.VALOR_1) * 100, 2)

I was hoping it would return a percentage, but it returns an ERROR instead... Any ideas on what's wrong?


Solution

  • Depending on your inputs you can try addapting this solution :

    CREATE TABLE #TMP (
        val1 int,
        val2 int
    );
    
    INSERT INTO #TMP
    VALUES (1,2),(1,3),(1,4),(2,5),(2,6)
    
    GO
    -- Your code begins here
    WITH tmp_table AS (
        SELECT
            val1 AS val1,
            SUM(COLAESCE(val2, 0)) AS sum_val2
        FROM #TMP
        GROUP BY val1,val2
    )
    SELECT ROUND((sum_val2 - val1)/val1,2) FROM tmp_table;
    -- Your code ends here
    GO
    
    DROP TABLE #TMP