Division ( / ) not giving my answer in postgresql - sql

I have a table software and columns in it as dev_cost, sell_cost. If dev_cost is 16000 and sell_cost is 7500, how do I find the quantity of software to be sold in order to recover the dev_cost?
I have queried as below:
select dev_cost / sell_cost from software ;
It is returning 2 as the answer. But we need to get 3, right?
What would be the query for that?

Your columns have integer types, and integer division truncates the result towards zero. To get an accurate result, you'll need to cast at least one of the values to float or decimal:
select cast(dev_cost as decimal) / sell_cost from software ;
or just:
select dev_cost::decimal / sell_cost from software ;
You can then round the result up to the nearest integer using the ceil() function:
select ceil(dev_cost::decimal / sell_cost) from software ;
(See demo on SQLFiddle.)

You can cast integer type to numeric and use ceil() function to get the desired output
The PostgreSQL ceil function returns the smallest integer value that
is greater than or equal to a number.
SELECT 16000::NUMERIC / 7500 col
,ceil(16000::NUMERIC / 7500)
Result:
col ceil
------------------ ----
2.1333333333333333 3
So your query should be
select ceil(dev_cost::numeric/sell_cost)
from software

You can also cast your variable to the desired type, then apply division:
SELECT (dev_cost::numeric/sell_cost::numeric);
You can round your value , and specify the number of digits after point:
SELECT TRUNC((dev_cost::numeric/sell_cost::numeric),2);

This query will round result to next integer
select round(dev_cost ::decimal / sell_cost + 0.5)

Related

Why doesn't ROUND(23/6) = 4 in SQL?

Case A: When you are trying to round the result yourself to the nearest decimal
SELECT ROUND (3.833333333333333) -- 4
Case B: When you let SQL do the math and then round to the nearest decimal
SELECT ROUND (23/6) -- 3 (OR CEIL)
In this case according to the order of operations:
SQL will divide what’s between the parenthesis, first = 3.833333333333333
And then (This is the problem) it will erase everything in the decimal places. (Converting it to int, automatically) =3.0
Now, let's round the decimals (Which are already erased in the previous step! And now it’s = 0)
So, the last result will be (3). Not (4).!
Even with conversions:
SELECT CAST (DIV (23,6) AS NUMERIC (10,5)) AS tst -- 3.00000
SELECT CAST ((23/6) AS DECIMAL (5,2)) AS tst -- 3.00
SELECT CAST (23/6 AS FLOAT) AS tst -- 3
SELECT CAST (23/6 AS REAL) AS tst -- 3
Is there a solution to this problem ?
Because it performs integer division. When then engine evaluates:
ROUND (23/6)
the expression 23/6 is evaluated first as 3. Then:
ROUND (3)
is evaluated as 3.
If you want the float precision you can multiply by 1.0. For example by doing:
ROUND ( 1.0 * 23/6)

Sum column only 2 digits after precision (no round)

I have a float type column with numbers that have 6 digits after precision. I want to sum the column only by 2 digits after precision.
For example, I have 1.257868 and 1.258778 as values and I want to get the result of 2.50 as result of sum.
It looks like you want something like:
sum(floor(mycol * 100) / 100)
The expression within the sum() performs the truncation to 2 decimals.
You can use the 3 argument form of round():
select sum(round(mycol, 2, 1))
odbc truncate
select v.val, {fn TRUNCATE(v.val, 2)} as trncted, sum({fn TRUNCATE(v.val, 2)}) over() as sumtrncated
from
(values (1.257868), (1.258778)) as v(val);

SQL Cast to show decimals

I have the following statement within my select clause;
(([Complt_Emp] + [No_Non_Complt_Emp])/ [No_of_Emp]) as Total_Completed
How do I implement CAST "cast(your_float_column as decimal(10,2))" ? I want my column Total_Completed to show 2 decimal places
I cannot seem to get the correct syntax!
Thank you
the result of the calculation depends of the used columns type.
If you divide int columns, you get int result : 1 / 6 = 0
when you convert each values to decimal the result is: 1 / 6 = 0.1666666666666
Now you want 2 decimal result,so you have to convert/ round the previous result to get the expected value
See fiddle for some example of divide and cast / round : http://sqlfiddle.com/#!18/51785/5
An easy trick can be to use :
round ( 1.0 * ( [Complt_Emp] + [No_Non_Complt_Emp] ) / [No_of_Emp] , 2 )
Cast each expression seperately
CAST(([Complt_Emp] + [No_Non_Complt_Emp]) as decimal(10,2)) /
CAST([No_of_Emp] as decimal(10,2)) as Total_Completed
I suspect all your values are INT. An int divided by an int will return an int.
(([Complt_Emp] + [No_Non_Complt_Emp])/ cast([No_of_Emp] as decimal(10,2)) as Total_Completed
Try this
cast((([Complt_Emp] + [No_Non_Complt_Emp])/ [No_of_Emp]) as decimal(10,2)) as Total_Completed

Rounding of the numeric values

I want to round of the values of two columns:
select a.region as "Regions",
a.suminsured,2 as "SumInsured" ,
a.suminsured/b.sum*100 as pct
from (
SELECT region, sum(suminsured) as suminsured
FROM "Exposure_commune" group by region
) a,
(select sum(suminsured) FROM "Exposure_commune") b
I want the suminsured and pct columns to come with 2 decimal places. Can someone tell me what I should do?
You can use directly numeric with two parameters. Second parameter for round decimal.
select sum(column_name::numeric(10,2)) from tablename
Use round() with two parameters, which only works for the data type numeric.
While being at it, your query can be simpler and faster:
SELECT region
, round(sum(suminsured), 2) AS suminsured
, round((sum(suminsured) * 100) / sum(sum(suminsured)) OVER (), 2) AS pct
FROM "Exposure_commune"
GROUP BY 1;
You can use sum() as window function to get the total without additional subquery, which is cheaper. Related:
Postgres window function and group by exception
Multiplying first is typically cheaper and more exact (although that barely matters with numeric).
Data type is not numeric
For data types double precision of real
You can ...
just cast to numeric to use the same function.
multiply by 100, cast to integer and divide by 100.0.
multiply by 100 and use the simple round() and devide by 100.
The simple round() with just one parameter works for floating point types as well.
Demonstrating all three variants:
SELECT region
, round(sum(suminsured), 2) AS suminsured
, (sum(suminsured) * 100)::int / 100.0 AS suminsured2
, round(sum(suminsured) * 100) / 100 AS suminsured3
, round((sum(suminsured) * 100) / sum(sum(suminsured)) OVER (), 2) AS pct
, ((sum(suminsured) * 10000) / sum(sum(suminsured)) OVER ())::int / 100.0 AS pct2
, round((sum(suminsured) * 10000) / sum(sum(suminsured)) OVER ()) / 100 AS pct3
FROM "Exposure_commune"
GROUP BY 1;
SQL Fiddle.

Truncate (not round) decimal places in SQL Server

I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:
declare #value decimal(18,2)
set #value = 123.456
This will automatically round #value to be 123.46, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the left() function and convert back to a decimal. Are there any other ways?
ROUND ( 123.456 , 2 , 1 )
When the third parameter != 0 it truncates rather than rounds.
Syntax
ROUND ( numeric_expression , length [ ,function ] )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data
type category, except for the bit data type.
length
Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.
function
Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
select round(123.456, 2, 1)
SELECT Cast(Round(123.456,2,1) as decimal(18,2))
Here's the way I was able to truncate and not round:
select 100.0019-(100.0019%.001)
returns 100.0010
And your example:
select 123.456-(123.456%.001)
returns 123.450
Now if you want to get rid of the ending zero, simply cast it:
select cast((123.456-(123.456%.001)) as decimal (18,2))
returns 123.45
Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.
CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))
Do you want the decimal or not?
If not, use
select ceiling(#value),floor(#value)
If you do it with 0 then do a round:
select round(#value,2)
Another truncate with no rounding solution and example.
Convert 71.950005666 to a single decimal place number (71.9)
1) 71.950005666 * 10.0 = 719.50005666
2) Floor(719.50005666) = 719.0
3) 719.0 / 10.0 = 71.9
select Floor(71.950005666 * 10.0) / 10.0
Round has an optional parameter
Select round(123.456, 2, 1) will = 123.45
Select round(123.456, 2, 0) will = 123.46
ROUND(number, decimals, operation)
number => Required. The number to be rounded
decimals => Required. The number of decimal places to round number to
operation => Optional. If 0, it rounds the result to the number of decimal. If another value than 0, it truncates the result to the number of decimals. Default value is 0
SELECT ROUND(235.415, 2, 1)
will give you 235.410
SELECT ROUND(235.415, 0, 1)
will give you 235.000
But now trimming0 you can use cast
SELECT CAST(ROUND(235.415, 0, 1) AS INT)
will give you 235
This will remove the decimal part of any number
SELECT ROUND(#val,0,1)
SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;
Would give you 2 values after the decimal point. (MS SQL SERVER)
Another way is ODBC TRUNCATE function:
DECLARE #value DECIMAL(18,3) =123.456;
SELECT #value AS val, {fn TRUNCATE(#value, 2)} AS result
LiveDemo
Output:
╔═════════╦═════════╗
║ val ║ result ║
╠═════════╬═════════╣
║ 123,456 ║ 123,450 ║
╚═════════╩═════════╝
Remark:
I recommend using built-in ROUND function with 3rd parameter set to 1.
I know this is pretty late but I don't see it as an answer and have been using this trick for years.
Simply subtract .005 from your value and use Round(#num,2).
Your example:
declare #num decimal(9,5) = 123.456
select round(#num-.005,2)
returns 123.45
It will automatically adjust the rounding to the correct value you are looking for.
By the way, are you recreating the program from the movie Office Space?
Try like this:
SELECT cast(round(123.456,2,1) as decimal(18,2))
If you desire to take some number like 89.0904987 and turn it into 89.09 by simply omitting the undesired decimal places, simply use the following:
select cast(yourColumnName as decimal(18,2))
The following screenshot is from W3Schools SQL Data Types section, which describes what decimal(18,2) is doing:
Therefore,
select cast(89.0904987 as decimal(18,2))
gives you: 89.09
Please try to use this code for converting 3 decimal values after a point into 2 decimal places:
declare #val decimal (8, 2)
select #val = 123.456
select #val = #val
select #val
The output is 123.46
I think you want only the decimal value,
in this case you can use the following:
declare #val decimal (8, 3)
SET #val = 123.456
SELECT #val - ROUND(#val,0,1)
I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):
SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)
I think we can go much easier with simpler example solution found in Hackerrank:
Problem statement: Query the greatest value of the Northern Latitudes
(LAT_N) from STATION that is less than 137.2345. Truncate your answer
to 4 decimal places.
SELECT TRUNCATE(MAX(LAT_N),4)
FROM STATION
WHERE LAT_N < 137.23453;
Solution Above gives you idea how to simply make value limited to 4 decimal points. If you want to lower or upper the numbers after decimal, just change 4 to whatever you want.
Mod(x,1) is the easiest way I think.
select convert(int,#value)