Math in SQL query not working - sql

I have a sql query (SQL server 2005) that's creating a var and doing some math. The math works when the ticket count is 0 or 250000, but it's not creating a decimal point when the ticket count is any other value. (It reads 0.) Here is the query -
SELECT ticketCount, ((250000 - ticketCount) / 250000) * 100 AS percentSold
FROM raffleTickets
Where ticketCount in the DB is how many tickets of 250000 remain to be sold. If ticketCount is 250000, percentsold is 0, which is correct. If ticketCount is 0, percentSold is 100, which is correct. For all other values, percentSold is returning 0.
Please help! Thanks.

SQL Server does integer division (this varies among databases).
You can easily fix this by putting a decimal point after the constants:
SELECT ticketCount, ((250000.0 - ticketCount) / 250000.0) * 100.0 AS percentSold
FROM raffleTickets;
If you want the integer portion, then you can cast() the result back to an integer. Alternatively, you can use the str() function to convert the value of percentSold to a string with the appropriate number of decimal points.

Your formula is correct,
PercentSold = (TotalTickets - TicketsRemaining) / TotalTickets
But what is the Domain and Range of the above function? Your numbers are all expressed as integer, but you probably want to calculate using Real.
PercentSold = ( ( TotalTickets - TicketsRemaining )*100.0) / (TotalTickets)
This forces the calculation to be done in Real. Languages that know how to declare variables and calculations in specific types (i.e. Domains) can make this clearer, more apparent.
Wanting to represent a real number with a certain precision means you want to perform output formatting. SqlServer must have a way to specify output format for numbers in the Real Domain. I defer to SqlZoo.net for their answer to formatting.

The only thing you need to do is putting plus or minus 0.0 in your formula.
SELECT ticketCount, ((250000 - ticketCount - 0.0) / 250000) * 100 AS percentSold
FROM raffleTickets

Related

Float precision in Bigquery [duplicate]

We don't have decimal data type in BigQuery now. So I have to use float
But
In Bigquery float division
0.029*50/100=0.014500000000000002
Although
0.021*50/100=0.0105
To round the value up
I have to use round(floatvalue*10000)/10000.
Is this the right way to deal with decimal data type now in BigQuery?
Depends on your coding preferences - for example you can just use simple ROUND(floatvalue, 4)
Depends on how exactly you need to round - up or down - you can respectively adjust expression
For example ROUND(floatvalue + 0.00005, 4)
See all rounding functions for BigQuery Standard SQL at below link
https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#rounding-functions
Note that this question deserves a different answer now.
The premise of the question is "We don't have decimal data type in BigQuery now."
But now we do: You can use NUMERIC:
SELECT CAST('0.029' AS NUMERIC)*50/100
# 0.0145
Just make your column is NUMERIC instead of FLOAT64, and you'll get the desired results.
Rounding up in most SQL dialects is not a built-in function unless you're fortunate enough to be rounding up to an integer. In this case, CEIL is a quick and reliable solution.
In the case of rounding decimals up, we can also leverage CEIL, albeit with a couple of additional steps.
The procedure:
Multiply your value to move the last decimal to the tenths position. Ex. 18.234 becomes 1823.4 by multiplying by 100. (n * 100)
Use CEIL() to round up to the nearest integer. In our example, CEIL(n) = 1824.
Divide this result by the same figure used in step 1. In our example, n / 100 = 18.24.
Simplifying these steps leaves us with the below logic:
SELECT CEIL(value * 100) / 100 as rounded_up;
The same logic can be used to round down using the FLOOR function as such:
FLOOR(value * 100) / 100 AS rounded_down;
Thanks to #Mureinik for this answer.

SQL Percent Error. Trouble with trying to use ABS()

I am trying to find the Percent error of two columns for each row.
Currently I tried
UPDATE Weather
SET PercentError=ActualTemp - ForecastTemp / ActualTemp * 100
Which I know is in correct because when i do the calculations it doesn't match up with what the sql gives me. I then tried to use something along the lines of
UPDATE Weather
SET PercentError=ABS (ActualTemp - ForecastTemp) / ActualTemp * 100
But when i do this I just get 0 for my Percent error. I used ABS because I know it works with an INT but wanted to see if it would work when subtracting two columns.
I have been looking up how to subtract two columns using abs but they just use ABS to turn their number into positive and never use it in the equation itself. Is anyone able to point me in the right direction on how to get this to work correctly?
*Using Microsoft sql server
It's doing integer calculations. Try floating point math:
UPDATE Weather
SET PercentError=
(100.0 * ABS (ActualTemp - ForecastTemp)) / ActualTemp
Note that I placed the 100 in front of the equation, and forced the multiplication before the division.
How bout fixing the parentheses?
UPDATE Weather
SET PercentError = (ActualTemp - ForecastTemp) * 100.0 / ActualTemp ;
The 100.0 ensures that the division is not integer division.
Negative numbers seem reasonable, but you can include ABS():
UPDATE Weather
SET PercentError = ABS(ActualTemp - ForecastTemp) * 100.0 / ActualTemp ;

How to use bigquery round up results to 4 digits after decimal point?

We don't have decimal data type in BigQuery now. So I have to use float
But
In Bigquery float division
0.029*50/100=0.014500000000000002
Although
0.021*50/100=0.0105
To round the value up
I have to use round(floatvalue*10000)/10000.
Is this the right way to deal with decimal data type now in BigQuery?
Depends on your coding preferences - for example you can just use simple ROUND(floatvalue, 4)
Depends on how exactly you need to round - up or down - you can respectively adjust expression
For example ROUND(floatvalue + 0.00005, 4)
See all rounding functions for BigQuery Standard SQL at below link
https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#rounding-functions
Note that this question deserves a different answer now.
The premise of the question is "We don't have decimal data type in BigQuery now."
But now we do: You can use NUMERIC:
SELECT CAST('0.029' AS NUMERIC)*50/100
# 0.0145
Just make your column is NUMERIC instead of FLOAT64, and you'll get the desired results.
Rounding up in most SQL dialects is not a built-in function unless you're fortunate enough to be rounding up to an integer. In this case, CEIL is a quick and reliable solution.
In the case of rounding decimals up, we can also leverage CEIL, albeit with a couple of additional steps.
The procedure:
Multiply your value to move the last decimal to the tenths position. Ex. 18.234 becomes 1823.4 by multiplying by 100. (n * 100)
Use CEIL() to round up to the nearest integer. In our example, CEIL(n) = 1824.
Divide this result by the same figure used in step 1. In our example, n / 100 = 18.24.
Simplifying these steps leaves us with the below logic:
SELECT CEIL(value * 100) / 100 as rounded_up;
The same logic can be used to round down using the FLOOR function as such:
FLOOR(value * 100) / 100 AS rounded_down;
Thanks to #Mureinik for this answer.

How do I count decimal places in SQL?

I have a column X which is full of floats with decimals places ranging from 0 (no decimals) to 6 (maximum). I can count on the fact that there are no floats with greater than 6 decimal places. Given that, how do I make a new column such that it tells me how many digits come after the decimal?
I have seen some threads suggesting that I use CAST to convert the float to a string, then parse the string to count the length of the string that comes after the decimal. Is this the best way to go?
You can use something like this:
declare #v sql_variant
set #v=0.1242311
select SQL_VARIANT_PROPERTY(#v, 'Scale') as Scale
This will return 7.
I tried to make the above query work with a float column but couldn't get it working as expected. It only works with a sql_variant column as you can see here: http://sqlfiddle.com/#!6/5c62c/2
So, I proceeded to find another way and building upon this answer, I got this:
SELECT value,
LEN(
CAST(
CAST(
REVERSE(
CONVERT(VARCHAR(50), value, 128)
) AS float
) AS bigint
)
) as Decimals
FROM Numbers
Here's a SQL Fiddle to test this out: http://sqlfiddle.com/#!6/23d4f/29
To account for that little quirk, here's a modified version that will handle the case when the float value has no decimal part:
SELECT value,
Decimals = CASE Charindex('.', value)
WHEN 0 THEN 0
ELSE
Len (
Cast(
Cast(
Reverse(CONVERT(VARCHAR(50), value, 128)) AS FLOAT
) AS BIGINT
)
)
END
FROM numbers
Here's the accompanying SQL Fiddle: http://sqlfiddle.com/#!6/10d54/11
This thread is also using CAST, but I found the answer interesting:
http://www.sqlservercentral.com/Forums/Topic314390-8-1.aspx
DECLARE #Places INT
SELECT TOP 1000000 #Places = FLOOR(LOG10(REVERSE(ABS(SomeNumber)+1)))+1
FROM dbo.BigTest
and in ORACLE:
SELECT FLOOR(LOG(10,REVERSE(CAST(ABS(.56544)+1 as varchar(50))))) + 1 from DUAL
A float is just representing a real number. There is no meaning to the number of decimal places of a real number. In particular the real number 3 can have six decimal places, 3.000000, it's just that all the decimal places are zero.
You may have a display conversion which is not showing the right most zero values in the decimal.
Note also that the reason there is a maximum of 6 decimal places is that the seventh is imprecise, so the display conversion will not commit to a seventh decimal place value.
Also note that floats are stored in binary, and they actually have binary places to the right of a binary point. The decimal display is an approximation of the binary rational in the float storage which is in turn an approximation of a real number.
So the point is, there really is no sense of how many decimal places a float value has. If you do the conversion to a string (say using the CAST) you could count the decimal places. That really would be the best approach for what you are trying to do.
I answered this before, but I can tell from the comments that it's a little unclear. Over time I found a better way to express this.
Consider pi as
(a) 3.141592653590
This shows pi as 11 decimal places. However this was rounded to 12 decimal places, as pi, to 14 digits is
(b) 3.1415926535897932
A computer or database stores values in binary. For a single precision float, pi would be stored as
(c) 3.141592739105224609375
This is actually rounded up to the closest value that a single precision can store, just as we rounded in (a). The next lowest number a single precision can store is
(d) 3.141592502593994140625
So, when you are trying to count the number of decimal places, you are trying to find how many decimal places, after which all remaining decimals would be zero. However, since the number may need to be rounded to store it, it does not represent the correct value.
Numbers also introduce rounding error as mathematical operations are done, including converting from decimal to binary when inputting the number, and converting from binary to decimal when displaying the value.
You cannot reliably find the number of decimal places a number in a database has, because it is approximated to round it to store in a limited amount of storage. The difference between the real value, or even the exact binary value in the database will be rounded to represent it in decimal. There could always be more decimal digits which are missing from rounding, so you don't know when the zeros would have no more non-zero digits following it.
Solution for Oracle but you got the idea. trunc() removes decimal part in Oracle.
select *
from your_table
where (your_field*1000000 - trunc(your_field*1000000)) <> 0;
The idea of the query: Will there be any decimals left after you multiply by 1 000 000.
Another way I found is
SELECT 1.110000 , LEN(PARSENAME(Cast(1.110000 as float),1)) AS Count_AFTER_DECIMAL
I've noticed that Kshitij Manvelikar's answer has a bug. If there are no decimal places, instead of returning 0, it returns the total number of characters in the number.
So improving upon it:
Case When (SomeNumber = Cast(SomeNumber As Integer)) Then 0 Else LEN(PARSENAME(Cast(SomeNumber as float),1)) End
Here's another Oracle example. As I always warn non-Oracle users before they start screaming at me and downvoting etc... the SUBSTRING and INSTRING are ANSI SQL standard functions and can be used in any SQL. The Dual table can be replaced with any other table or created. Here's the link to SQL SERVER blog whre i copied dual table code from: http://blog.sqlauthority.com/2010/07/20/sql-server-select-from-dual-dual-equivalent/
CREATE TABLE DUAL
(
DUMMY VARCHAR(1)
)
GO
INSERT INTO DUAL (DUMMY)
VALUES ('X')
GO
The length after dot or decimal place is returned by this query.
The str can be converted to_number(str) if required. You can also get the length of the string before dot-decimal place - change code to LENGTH(SUBSTR(str, 1, dot_pos))-1 and remove +1 in INSTR part:
SELECT str, LENGTH(SUBSTR(str, dot_pos)) str_length_after_dot FROM
(
SELECT '000.000789' as str
, INSTR('000.000789', '.')+1 dot_pos
FROM dual
)
/
SQL>
STR STR_LENGTH_AFTER_DOT
----------------------------------
000.000789 6
You already have answers and examples about casting etc...
This question asks of regular SQL, but I needed a solution for SQLite. SQLite has neither a log10 function, nor a reverse string function builtin, so most of the answers here don't work. My solution is similar to Art's answer, and as a matter of fact, similar to what phan describes in the question body. It works by converting the floating point value (in SQLite, a "REAL" value) to text, and then counting the caracters after a decimal point.
For a column named "Column" from a table named "Table", the following query will produce a the count of each row's decimal places:
select
length(
substr(
cast(Column as text),
instr(cast(Column as text), '.')+1
)
) as "Column-precision" from "Table";
The code will cast the column as text, then get the index of a period (.) in the text, and fetch the substring from that point on to the end of the text. Then, it calculates the length of the result.
Remember to limit 100 if you don't want it to run for the entire table!
It's not a perfect solution; for example, it considers "10.0" as having 1 decimal place, even if it's only a 0. However, this is actually what I needed, so it wasn't a concern to me.
Hopefully this is useful to someone :)
Probably doesn't work well for floats, but I used this approach as a quick and dirty way to find number of significant decimal places in a decimal type in SQL Server. Last parameter of round function if not 0 indicates to truncate rather than round.
CASE
WHEN col = round(col, 1, 1) THEN 1
WHEN col = round(col, 2, 1) THEN 2
WHEN col = round(col, 3, 1) THEN 3
...
ELSE null END

Get an accurate percentage calculation

I am trying to divide one number by another in a SQL view. I'm dividing two columns that are each of type int, and the problem is that its giving me a rounded output, rather than an accurate one.
Here is my select:
SELECT numberOne, numberTwo, (numberOne*100/NULLIF(numberTwo, 0)) as PctOutput
This is working, but when it dives 3 by 37 its giving me 8 instead of 8.108.
How would I modify this to give me an accurate answer? Do I need to cast the numbers out of ints? if so - into what?
Try an implicit cast:
SELECT
numberOne,
numberTwo,
((1.0*numberOne)*100/NULLIF(1.0*numberTwo, 0)) as PctOutput
**--Cast the denominator as Float**
SELECT 3 * 100 / NULLIF(CAST(37 AS FLOAT),0) -- 8.10810810810811
**--Multiply by 1.0 in either numerator OR denominator**
SELECT 3 * 100 / NULLIF(37 * 1.0,0) -- 8.108108
SELECT 3.0 * 100 / NULLIF(37,0) -- 8.108108
**--Convert it to decimal**
SELECT CONVERT(DECIMAL(25,13), 3) * 100 /
NULLIF(CONVERT(DECIMAL(25,13), 37),0) -- 8.108108108
You need to cast the numbers from INT into either float or decimal.
If you use literals, they will likely be decimal (NUMERIC), not float (http://stackoverflow.com/questions/1072806/sql-server-calculation-with-numeric-literals)
Note that if you use decimal, you should be aware of the rules of scale and precision in division if you have numbers near the boundaries where you might lose precision:
http://msdn.microsoft.com/en-us/library/ms190476.aspx
In SQL Server the result is always of the same type as the inputs. So yes you do need to convert the inputs.
I generally convert using convert(decimal(9,2),numberOne) but depending you may want to convert(real,numberOne) or use a different level of precision.