Casting as decimal not acting as expected - sql

I am new to SQL and I am trying to calculate percentage from two pre-calculated numbers. I want the percentage to be at 2 decimal points. The numbers are integers so I am casting them as decimals before the percentage calculation. The calculation is simply
(Risk1/GrandTotal *100) both from the same table.
A piece of the code is given below:
SELECT risk_date_day,
((CAST(Risk1 as decimal(38,2))/CAST(GrandTotal as decimal(38,2))) * 100) FROM DPRAT2_Export
The result shows 6 numbers after the decimal
I have tried many different numbers for the parameters of decimal(x,x). I understood from research that the 2nd number is scale and that specifies the number of places after the decimal. I am not sure why the result has 6 decimal places. Please help. Thanks!

Do the cast() after the division:
SELECT risk_date_day,
CAST(Risk1 * 100.0 / GrandTotal as decimal(38, 2))
FROM DPRAT2_Export;
SQL in general and SQL Server in particular has very arcane rules for determining the number of decimal points in the result of mathematical operations on decimals. So, just convert the result.
If there is the risk that GrandTotal might be zero, I would advise:
SELECT risk_date_day,
CAST(Risk1 * 100.0 / NULLIF(GrandTotal, 0) as decimal(38, 2))
FROM DPRAT2_Export;
This prevents the divide-by-zero error, returning NULL instead.

Related

Division to output calculation value

Is there a different way in which I can wrap or write the calculation in the query below so that it divides properly besides using round (100.0 * ...) ?
SELECT ROUND(100.0 * COUNT(DISTINCT c.user_id) / COUNT(DISTINCT b.user_id)) AS browse_to_checkout_percent
Thanks!
I'm assuming what you mean by not dividing properly is the fact you're getting unexpected results due to dividing integers. When SQL does math on integers it returns an integer as a result. This means any decimal result is cut off.
So take the query
SELECT 50/100
You would expect a result of 0.5 however since .5 is not an integer you get a result of 0
Likewise with
SELECT 101/100
You would expect a result of 1.01 but you get a result of 1.
COUNT returns an integer so when you do division between the two integers the result is the same as above.
What you need to do with your query is to cast or convert what count returns as another data type. Which datatype you choose depends on a few factors but for what you are doing I would say float will do.
SELECT CAST(COUNT(DISTINCT c.user_id) as FLOAT) / CAST(COUNT(DISTINCT b.user_id) as FLOAT) AS browse_to_checkout_percent
For simplicity I've removed ROUND but you can add that in as needed.
For more info you can see this blog post.

SQL Calculation to 2 decimal places

I've got a simple calculation (910 / 28 = 3.5) and I'm trying to perform this in a SQL query:
SELECT CONVERT(DECIMAL(5,2), (910 / 28),2) AS average
But the answer is coming out at 32.00, I'm obviously missing something simple could someone spare a moment to point out my error please?
Thanks,
C
Use this:
SELECT CONVERT(DECIMAL(5,2), (910.0 / 28)) AS average
By taking the quotient as 910.0 / 28 SQL Server will retain decimal precision. Then, make your cast to a decimal with two places. By the way, as far as I know CONVERT typically takes just two parameters when converting a number to decimal.
we can use this query for dynamic value from table:
SELECT CONVERT(DECIMAL(5,2), (cast (910 as decimal))/ 28) AS average
It will give the desire output
Unsure if this applies to your database, but in Trino SQL (a sort of database middleware layer), I find adding a decimal point followed by two zeros to any of two operands in this query (e.g., select 910.00/23 AS average or select 910/23.00 AS average) returns a non-integer value (39.57, instead of 39).
Adding 3 zeros after the decimal (select 910.000/23 AS average) returns a 3-decimal place result (39.565), and so on.
Try this query...
SELECT CAST(910 AS decimal(5,2)) / CAST(28 AS decimal(5,2)) as average
Try use this
select cast(round(910/28.0,2) as numeric(36,2)) AS average

How to calculate decimal(x, y) max value in SQL Server

How do I know the maximum value of decimal type?
For example:
decimal(5, 2)
Can you please explain the mechanism of decimal type?
The maximum possible value can be calculated using the following maths:
(10 ^ (x-y)) - (10 ^ -y)
So in your initial example
(10 ^ (5-2)) - (10 ^ -2) = 1000 - 0.01 = 999.99
I'm adding this answer as my google results took me here when trying to remind myself how to calculate the SQL friendly upper bounds of a C# decimal going into an SQL (28,10) decimal field.
999999999999999999.9999999999 by the way.
You can use an aggregate function in order to get the maximum value in a column
SELECT MAX(myColumn) AS MyColumnMax
FROM myTable
If you want to know the maximum value for each customer for instance, you can group by this customer
SELECT CustomerID, MAX(OrderAmount) AS MaxOrderAmount
FROM CustomerOrders
GROUP BY CustomerID
You can find other aggregate functions here.
If, by contrast, you are interested in range of a decimal type, then consider, that you are declaring the total number of digits and decimals. Therefore the maximum number is reached, when all these digits are 9.
So for decimal(5,2) it would be 999.99. 5 is the total number of decimals to the left and to the right of the decimal point. 2 is the number of decimals to the right of the decimal point.
The maximum possible range for decimals is -10^38 + 1 through 10^38 - 1.

Sum function doesn't give sufficient decimal places with divide function

I have the following sql query that I am running:
select sum(cast(mkt_value as decimal(20,7)))/1204438043.37 from table1
and I get the following result which is correct but I need at least 10 decimal places not 6:
0.009347
If I run the following query:
select sum(mkt_value) from table1
I get 11258490.2400.
If I divide 11258490.24 by 1204438043.37 in excel I get 0.009347504674 which is the answer I'm looking for.
Please help me correct my SQL!!
Your cast is breaking this. It doesn't have enough space to give you more than six decimal places. What you're saying is literally "give me the result of this division with at most six decimal places", and then you're suprised the result only has six decimal places :)
The solution is either to omit the cast (if the data type is money, it's fine) or increase the scale of the decimal, eg. decimal(20, 11). The second parameter of the decimal type says the maximal amount of decimal places (-1) in the number. Also, consider only casting the result of the sum instead of all the items.
Note that most operations in MS SQL return a value of the same data type. So:
select 3 / 4; -- Returns 0
select cast(1000 as smallint) * cast(1000 as smallint);
-- Error - 1 000 000 is too big for smallint
The same thing happens in your sum and also in the division that happens right after it :)
You need to apply casting after calculating final value
select CAST (sum(mkt_value)/1204438043.37 as decimal(15,10)) from table1.
This means result would be having maximum 15 digits and mandatory 10 decimal places.
I would suggest the following query,Since your final decimal places are getting truncated.Hence a cast would be required to your final result set.
select
cast(cast (sum(mkt_value) as decimal(20,7))/cast (1204438043.37 as decimal(20,7)) as decimal(20,12)) from table1
Thank you..Let me know if this works

Arithmetic overflow error converting numeric datatype to numeric

I'm having following columns in a table
SIZE NUMERIC(14,5)
PRICE NUMERIC(14,5)
when I perform this select query,
SELECT SIZE,
PRICE,
SIZE*PRICE AS TOTAL
FROM TNAME
I'm getting results:
1.00000 90.00000 90.0000000000
1.00000 90.00000 90.0000000000
1.00000 90.00000 90.0000000000
1.00000 100.00000 100.0000000000
1.00000 30.00000 30.0000000000
I'm wondering why the third column is returning with 10 digits after decimal point?
Also I'm getting
Arithmetic overflow error converting numeric datatype to numeric
while inserting result into another table which has the same columns with same datatype
INSERT INTO TNAME2(SIZE, PRICE, TOTAL)
SELECT
SIZE, PRICE, SIZE * PRICE AS TOTAL
FROM
TNAME
Try This.
SELECT SIZE,
PRICE,
CAST(SIZE*PRICE AS numeric(14,5))AS TOTAL
FROM TNAME
INSERT INTO TNAME2
SELECT SIZE ,
Price ,
CAST(SIZE * PRICE AS NUMERIC(15, 5))
FROM TNAME
OR
INSERT INTO TNAME2 (SIZE,Price,TOTAL)
SELECT SIZE ,
Price ,
CAST(SIZE * PRICE AS NUMERIC(15, 5)) AS TOTAL
FROM TNAME
Regarding the first question, the number of decimals, there is nothing wrong. It's the basic, everyday multiplication we learn at school: Multiplying two decimal numbers produces a number with as many decimal digits as the sum of decimal digits of the operands. The number of integer digits can be up to the sum of integer digits of the operands.
Multiplying 10.11 by 12.13 produces 122.6343. It would be VERY awkward if SQL Server broke this basic rule and arbitrarily truncated the result.
As a result, when you try to store the product in a column that accepts fewer digits, you get an overflow error. SQL Server won't change the number of digits automatically because there is no way to decide the correct action.
There are a lot of ways you can handle this, depending on the loss of precision you are willing to suffer:
Truncate the extra digits, ie throw them away, accepting up to a unit loss. This can become a LOT of money if you store totals.
Round to the desired number of digits. Sounds intuitive, but what about half-way values, ie 0.00005 in your case? Should it be 0.0001 or 0.0000? So we have
Rounding up, where 0.5 becomes 1, resulting in up to .5 loss per entry
Down, when it becomes 0, with the same loss
Round to even or odd, where you round to the nearest odd or even number, which on average produces minimal loss. While this sounds weird, it is the standard defined in IEEE 754. It's also called banker's rounding because it's used in bookkeeping to minimize losses due to truncation.
If you want to store fewer digits you need to decide whether you need to truncate the extra digits or how to round the number, then do it yourself in code.
In your case, you can use CAST to a numeric of the desired precision. This will perform rounding half up, where 0.00005 becomes 0.0001, eg:
INSERT INTO TNAME2(SIZE, PRICE, TOTAL)
SELECT
SIZE, PRICE, CAST(SIZE * PRICE as numeric(14,5)) AS TOTAL
FROM
TNAME
SQLFiddle here
This will work, assuming the number of digits doesn't exceed 14, otherwise you will have to change the type of your table field.
If you want some other kind of rounding in SQL, you will have to create your own function.
Got below useful link.
Multiplication of numerics
As per this link you can try as query as below
SELECT SIZE,
PRICE,
CAST(SIZE*PRICE AS numeric(28,5))AS TOTAL
FROM TNAME
Try this
SELECT SIZE,PRICE,CONVERT(numeric(14,5), SIZE*PRICE) AS TOTAL
FROM TNAME
Write the same query in insert, it must work