SQL Server How to perform maths arithmetic function?

tzcvj98z  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(107)

enter image description here

Find : max - min / min * 100

SELECT 
    *,
    MAX(Salary),
    MIN(Salary),
    MAX(Salary) - MIN(Salary)
FROM 
    Salary
GROUP BY
    empid

How to perform / operation ?

SELECT 
    *,
    MAX(Salary),
    MIN(Salary),
    ((MAX(Salary) - MIN(Salary)) / MIN(Salary))
FROM 
    Salary
GROUP BY
    empid

This is showing zero zero

mxg2im7a

mxg2im7a1#

I got the zeroes when trying your query in SQLite3 when I declared the Salary as INTEGER . You haven't shown the declaration of the table, though, so it's just a guess.

What helped was to cast the divisor as real:

SELECT empid, MAX(Salary), MIN(Salary),
       ((MAX(Salary) - MIN(Salary)) / CAST(MIN(Salary) AS REAL))
FROM Salary
GROUP BY empid;

But if you need to result multiplied by 100, you can just multiply the subtraction before doing the division:

SELECT empid, MAX(Salary), MIN(Salary),
       100 * (MAX(Salary) - MIN(Salary)) / MIN(Salary)
FROM Salary
GROUP BY empid;

相关问题