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??
1条答案
按热度按时间x0fgdtte1#
It's a type thing. Try this:
If
prCount = 5852
andtcCount = 125
then subtracting one from the other gives5727
.5727/5852
is0.978639
, however SQL Server is thinking this should be an integer so is truncating it at the decimal point to give0
.0 * 100
is also0
. By converting the first part of the calculation to a decimal it causes the rest of to be done using decimals as well hence the0.978639
isn't truncated.