I have a table called “Jrl” with three columns:
code AS varchar(15)
total AS numeric(13,2)
rem AS numeric(13,4)
Let us assume for the sake of the argument, that there is just one row in the table with values ‘001’, 400.00 and 52.1745.
Consider the following query:
SELECT code, total - rem
FROM Jrl
It returns one row with ‘001’ and 347.8255. This is correct.
If I change the query as follows (which is in fact the query I need in my code):
SELECT code, SUM(total) - SUM(rem)
FROM Jrl
GROUP BY code
It returns one row with ‘001’ and 347.83 (that is, with scale 2 instead of 4).
Now according to the documentation at http://msdn.microsoft.com/en-us/library/ms190476%28v=sql.90%29.aspx, the type of the numeric expression (subtraction) should be numeric(16,4), which it obviously isn’t. (I get the same behavior on SQL Server 2005 and 2008 R2.)
Can someone enlighten me as to what is happening there?
Btw. I did find a workaround, but I don’t like it which is why I am posting this question. The workaround would be to add an explicit cast:
SELECT code, CAST(SUM(total) AS numeric(13,4)) - SUM(rem)
FROM Jrl
GROUP BY code
1) Please run this script and read my comments.
2) I hope this answer will help you.
3) The precision for SUM()-SUM() is 2 because you choose first to sum(
SUM(total)andSUM(rem)) and then to subtract (SUM(total) - SUM(rem)).4) My advise is to use
SELECT t.code, SUM(t.total - t.rem) AS diff ...(first subtract and then SUM).5) You may read my answer to this question SQL Numeric data type truncating value?:
Results: