Postgres is giving the wrong result for division when the denominator is greater than the numerator.
select 2/4 gives 0, select 4/2 works correct.
But select 2/4 should actually return 0.5
but it is returning 0 as integer
Postgres does integer division on integers. Ironically, it does not do integer averages on avg(), but that is a different matter.
One solution is simply converting one of the value to numeric:
select 2/4, 2::numeric/4
Postgres will add decimal places for numerics.
Try a floating point division, as in:
select 2.0 / 4 -- shows 0.5
Or:
select 1.0 * 2 / 4 -- shows 0.5
Postgres is giving the wrong result for division when the denominator is greater than the numerator.
select 2/4 gives 0, select 4/2 works correct.
But select 2/4 should actually return 0.5
but it is returning 0 as integer
Postgres does integer division on integers. Ironically, it does not do integer averages on avg(), but that is a different matter.
One solution is simply converting one of the value to numeric:
select 2/4, 2::numeric/4
Postgres will add decimal places for numerics.
Try a floating point division, as in:
select 2.0 / 4 -- shows 0.5
Or:
select 1.0 * 2 / 4 -- shows 0.5
This question already has answers here:
How to get a float result by dividing two integer values using T-SQL?
(10 answers)
Closed 4 years ago.
I have a pretty simple breakdown of Customer names, and a corresponding count of that name. What I need is a third column which gives the percent of customers with that name.
Here's an example of what I need:
|NAME| |NAME_COUNT| |NAME_PERCENT|
Bob 5 41.7
John 4 33.3
Toby 3 25.0
I have the first two fields, but can't seem to nail down the percent.
The final part of my query looks like this:
SELECT
a.Name
a.Name_Count
FROM #NameTemp a
GROUP BY
a.Name,
a.Name_Count
ORDER BY
a.Name_Count DESC
I would think this would work in the select statement to get the percentage of each row, but it doesn't. It just gives me a value of 1 for every row in the Percent field:
a.Name_Count/SUM(a.NameCount) AS "Percent"
Just use window functions:
select name, name_count, name_count * 1.0 / sum(name_count) over ()
from #nametemp;
Note the * 1.0. SQL Server does integer division, so you need to convert to a format that has a decimal place.
I am guessing that you have an original table that is unaggregated. If so, doing this all in one query without a temporary table is a better solution:
select name, count(*) as name_count, count(*) * 1.0 / sum(count(*)) over ()
from names
group by name;
I'm trying to do something really quite basic to calculate a kind of percentage between two columns in Redshift. However, when I run the query with an example the result is simply zero because the decimals are not being covered.
code:
select 1701 / 84936;
Output:
I tried :
select cast(1701 / 84936 as numeric (10,10));
but the result was 0.0000000000.
How could I solve this silly thing?
It is integer division. Make sure that at least one argument is: NUMERIC(accurate data type)/FLOAT(caution: it's approximate data type):
/ division (integer division truncates the result)
select 1701.0 / 84936;
-- or
SELECT 1.0 * 1701 / 84936;
-- or
SELECT CAST(1701 AS NUMERIC(10,4))/84936;
DBFiddle Demo
When mixing data types the order counts
Note that the order of the elements in a math expression counts for the data type of the result.
Let's assume that we intend to calculate the percentage unit_sales/total_sales where both columns (or numbers) are integers.
See and try with this code here.
-- Some dummy table
drop table if exists sales;
create table sales as
select 3 as unit_sales, 9 as total_sales;
-- The calculations
select
unit_sales/total_sales*100, --> 0 (integer)
unit_sales/total_sales*100.0, --> 0.0 (float)
100.0*unit_sales/total_sales --> 33.3 (float and expected result)
from sales;
The output
0 | 0.0 | 33.33
The first column is 0 (integer) because of 3/9=0 in an integer division.
The second column is 0.0 because SQL first got the integer 0 (3/9), and later, SQL converts it to float in order to perform the multiplication by 100.0.
The expected result.
The non-integer 100.0 at the beginning of the expression force a non-integer calculation.
How can i convert this to a decimal in SQL? Below is the equation and i get the answer as 78 (integer) but the real answer is 78.6 (with a decimal) so i need to show this as otherwise the report won't tally up to 100%
(100 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
Try This:
(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
convert(decimal(5,2),(100 * convert(float,[TotalVisit1])/convert(float,[TotalVisits]))) AS Visit1percent
Ugly, but it works.
CAST(ROUND([TotalVisit1]*100.0/[TotalVisits],2)as decimal(5,2)) as Percentage
Not ugly and work better and fast , enjoy it!
At least in MySQL (if it helps), if you want to use float numbers you had to use a type float field, not the regular int fields.
Just add a decimal to the 100
(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
this forces all processing to happen in floats... if you want the final output as text, and truncated for display to only one decimal place, use Str function
Str( 100.0 * [TotalVisit1]/[TotalVisits], 4, 1 ) AS Visit1percent
This works perfectly for me:
CAST((1.0 * SUM(ColumnA) /COUNT(ColumnB)) as decimal(5,2))
Hope it helps someone out there in the world.
Its probably overkill to do this, but you may wish to consider casting all values to floats to ensure accuracy at all phases.
(100.0 * ( [TotalVisit1]+0.0 )/([TotalVisits]+0.0) ) as Visit1percent
Note, you really need to put code in here for the case that TotalVisits == 0 or you will get a division by 0 answer.
SELECT(ROUND(CAST(TotalVisit1 AS DECIMAL)/TotalVisits,1)) AS 'Visit1percent'
This will return a decimal and the ROUND will round it to one digit. So in your case you would get 76.6. If you don't want any digits change the 1 to 0 and if you want two digits change it to 2.
Try with this, no round and str or Over(). i found this as a simpler way to do it.
cast((count(TotalVisit1) * 100.0) /TotalVisits as numeric(5,3)) as [Visit1percent]
You can change the number of decimal points as you wish to
e.g. numeric(5,2) or numeric(5,4)
This might not address you issue directly, but when you round a set of numbers for display you're never guaranteed to get numbers that add to 100 unless you take special precautions. For example, rounding 33.33333, 33.33333 and 33.33333 is going to leave you one short on the sum, so the logical thing to do is to modify the percentage for the largest value in the set to take account of any difference.
Here's a way of doing that in Oracle SQL using analytic functions and a subquery factoring (WITH) clause to generate sample data.
with data as (select 25 num from dual union all
select 25 from dual union all
select 25 from dual)
select num,
case
when rnk = 1
then 100 - sum(pct) over (order by rnk desc
rows between unbounded preceding
and 1 preceding)
else pct
end pct
from
(
select num,
round(100*ratio_to_report(num) over ()) pct,
row_number() over (order by num desc) rnk
from data
)
/
NUM PCT
---------------------- ----------------------
25 33
25 33
25 34
In ms Access You can use the SQL function ROUND(number, number of decimals), It will round the number to the given number of decimals:
ROUND((100 * [TotalVisit1]/[TotalVisits]),1) AS Visit1percent