SQL Server % change between 2 columns values [duplicate]

rqdpfwrv  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(129)

This question already has answers here:

SQL division giving wrong answer [duplicate] (3 answers)
Closed 2 hours ago.

I am trying to get % change between 2 columns values in table. I am bit confused as to why % change is always returned as 0.

-- create
CREATE TABLE Host  
(
    HostName Varchar(100),
    tcCount int,
    PrCount int
);

-- insert
INSERT INTO Host (HostName, tcCount, prCount) 
VALUES ('AppServer04', 125, 5852);
INSERT INTO Host (HostName, tcCount, prCount) 
VALUES ('AppServer05', 300 , 4318);

-- fetch 
SELECT
    HostName, tcCount, PrCount,
    (prCount - tcCount) / prCount * 100 AS 'Change(%)' 
FROM 
    Host

Result I am getting of above is below:

HostName                                          tcCount     PrCount     Change(%)  
---------------------------------------------- ----------- ----------- -----------
AppServer04                                         125        5852           0
AppServer05                                         300        4318           0

(2 rows affected)

For AppServer04 % change should be 97.86 while AppServer05 should be 93.05. I am bit confused as to why I get 0 for both rows..

Am I missing anything here??

x0fgdtte

x0fgdtte1#

It's a type thing. Try this:

SELECT
    HostName, tcCount, PrCount,
    CONVERT(decimal, prCount - tcCount) / prCount * 100 AS 'Change(%)' 
FROM 
    Host

If prCount = 5852 and tcCount = 125 then subtracting one from the other gives 5727 . 5727/5852 is 0.978639 , however SQL Server is thinking this should be an integer so is truncating it at the decimal point to give 0 . 0 * 100 is also 0 . By converting the first part of the calculation to a decimal it causes the rest of to be done using decimals as well hence the 0.978639 isn't truncated.

相关问题