I have do select that contains a sum, I would like to convert the result (decimal) of the sum in integer result.
example:
137.5 in 1375
that any amount that I extract
it's possible?
Another way to do it would be to CAST it to VARCHAR, remove the . and then cast it back to an int
DECLARE #Value NUMERIC(18,3) = 15.435
SELECT CAST(REPLACE(CAST(#Value AS VARCHAR(100)),'.','') AS INT)
You can simply multiply it by 10 and cast it as int
If its SQL Server then it would be like
select cast((137.5*10.0) as int)
In general you can use it like
select cast((result*10) as int)
Note that I have assumed that the result has only one place of decimal.
Related
I want to convert my decimal SQL query result in percent. Example I have a 0.295333 I want it to be 30% and if I have a 0.090036 I want it to be 9%.
This is what I have so far.
(100 * (sample1/ sample2) ) as 'Percent'
I also tried this one but the problem is result comes with ".00" and I don't know how to remove the decimal.
cast (ROUND(100 * (sample1 / sample2),0) As int ) as 'Percent'
Try with the below script..
cast (100 * Round((sample1 / sample2),2) As int ) as 'Percent'
So as some of the comments pointed out you may need to pay attention to your datatype if one or both of the original columns that you get your decimal from are integer.
One easy way of dealing with that is something like this:
ColA * ColB * 1.0 which will make sure that your integers are treated as decimals
So if you have SQL Server 2012+ you can use Format and not mess with rounding at all. Like this FORMAT(YourDecimal,'#%'), yep that simple.
;WITH cteValues AS (
SELECT 0.295333 as OriginalValue
UNION ALL
SELECT 0.090036 as OriginalValue
)
SELECT
OriginalValue
,FORMAT(OriginalValue,'#%') as PercentFormat
FROm
cteValues
If you are pre 2012 and do not have format an easy way is to round to the 100th then times by 100 and cast as int CAST(ROUND(YourDecimal,2) * 100 AS INT)
;WITH cteValues AS (
SELECT 0.295333 as OriginalValue
UNION ALL
SELECT 0.090036 as OriginalValue
)
SELECT
OriginalValue
,CAST(ROUND(OriginalValue,2) * 100 AS INT) as PercentInt
FROm
cteValues
Because an INT cannot by definition have decimal places, if you are receiving .00 with the method similar to this or the one you have tried, I would ask the following.
Are you combining (multiplying etc.) the value after casting with another column or value that may be decimal, numeric, or float?
Are you looking at the query results in a program outside of SSMS that could be formatting the results automatically, e.g. Excel, Access?
Address your assumptions first.
How does ROUND work? Does it guarantee return values and if so, how? What is the precedence of the two columns? Does Arithmetic operators influence the results and how?
I only know what I do not know, and any doubt is worth an investigation.
THE DIVIDEND OPERATOR
Since ROUND always returns the higher precedence, this is not the problem. It is in fact the divide operator ( / ) that may be transforming your values to an integer.
Always verify the variables are consistently of one datatype or CAST if either unsure or unable to guarantee (such as insufficiently formatted. I.e. DECIMAL(4,2) instead of required DECIMAL(5,3) ).
DECLARE #Sample1 INT
, #Sample2 DECIMAL(4,2);
SET #Sample1 = 50;
SET #Sample2 =83.11;
SELECT ROUND( 100 * #Sample1 / #Sample2 , 0 )
Returns properly 60.
SELECT ROUND( 100 * #Sample2 / #Sample1 , 0)
Incorrectly turns variables into integers before rounding.
The reason is that DIVIDE - MSDN in SQL may return the higher precedence, but any dividend that is an integer returns another integer.
UPDATE
This also explains why the decimal remains after ROUND...it is of higher precedence. You can add another cast to transform the non-INT datatype to the preferred format.
SELECT CAST( ROUND( <expression>, <Length>) AS INT)
Note that in answering your question I learned something myself! :)
Hope this helps.
I have a table with numbers in a varchar(255) field. They're all greater than one and have multiple decimal places. I'd like to convert them to integers. According to every web site I've consulted, including this one on StackOverflow, either of these should work:
SELECT CAST(VarcharCol AS INT) FROM MyTable
SELECT CONVERT(INT, VarcharCol) FROM MyTable
These both work for me for every kind of numeric value but integer - I can convert to float, decimal, etc. just fine, but trying to convert to integer gives me the following error:
Conversion failed when converting the varchar value '7082.7758172'
to data type int.
I've worked around the problem by converting to data type Decimal(6,0), which works fine. But just for my education, can anyone tell me why converting to data type int (or integer) gives me an error? Thanks.
Converting a varchar value into an int fails when the value includes a decimal point to prevent loss of data.
If you convert to a decimal or float value first, then convert to int, the conversion works.
Either example below will return 7082:
SELECT CONVERT(int, CONVERT(decimal(12,7), '7082.7758172'));
SELECT CAST(CAST('7082.7758172' as float) as int);
Be aware that converting to a float value may result, in rare circumstances, in a loss of precision. I would tend towards using a decimal value, however you'll need to specify precision and scale values that make sense for the varchar data you're converting.
Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:
select cast ('7.0' as int)
select cast ('7.' as int)
will fail but both are fine for floats.
Presumably, you want to convert values before the decimal place to an integer. If so, use case and check for the right format:
SELECT (case when varcharcol not like '%.%' then cast(varcharcol as int)
else cast(left(varcharcol, chardindex('.', varcharcol) - 1) as int)
end) IntVal
FROM MyTable;
Try this
declare #v varchar(20)
set #v = 'Number'
select case when isnumeric(#v) = 1 then #v
else #v end
and
declare #v varchar(20)
set #v = '7082.7758172'
select case when isnumeric(#v) = 1 then #v
else convert(numeric(18,0),#v) end
Try this query:
SELECT cast(column_name as type) as col_identifier FROM tableName WHERE 1=1
Before comparing, the cast function will convert varchar type value to integer type.
SELECT
convert(numeric(18,5),Col1), Col2
FROM DBname.dbo.TableName
WHERE isnumeric(isnull(Col1,1)) <> 0
I have a data in the table in the form below and it is in varchar(8) datatype
Total
100
101
104.5
88
1038
64
108.3
10872
900
I like to use ASC in T-sql so that I can display it into ascending order, however I
cannot do it as it is in varchar(8) form
For example
select Total from
Table A
Order by Total ASC
How to first add these values into Temporary temp table?
and How to convert this varchar(8) values and into what? so that
you can display them in ASC or ascending order using T-SQL query?
Anyone?
You could cast the value like this.
SELECT
Total
FROM Table A
ORDER BY CAST(Total AS FLOAT) ASC
You may lose data converting back to float.
So here is a varchar based sort.
DECLARE #badDesign TABLE (floatcol varchar(8) NOT NULL);
INSERT #badDesign VALUES ('100'),('101'),('104.5'),('88'),('1038'),('64'),('108.3'),('10872'),('900'),('108'), ('108.32'), ('108.4')
SELECT *
FROM #badDesign
ORDER BY
RIGHT('00000000' +
CASE
WHEN CHARINDEX('.', floatcol) = 0 THEN floatcol
ELSE LEFT(floatcol, CHARINDEX('.', floatcol)-1)
END
, 8),
CASE
WHEN CHARINDEX('.', floatcol) = 0 THEN '.0'
ELSE SUBSTRING(floatcol, CHARINDEX('.', floatcol)+1, 8)
END
The values from your example looks like float numbers. So
1) Since they all have no more than 8 digits, you can cast it to float(53) (it has about 15 decimal digits precision) without loss of data. Or to decimal(15,7) to be completely sure.
2) Generally it's strange to store float values as strings in the database.
Use CAST or CONVERT functions, e.g.:
select Total from
Table A
Order by CAST(Total as float) ASC
Reference: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Unless you want to keep the converted values, you don't need to store it in a temporary table. Just convert them for the sorting:
select Total
from [Table A]
order by cast(Total as float)
(Ascending is the default way to sort, so you don't have to specify that.)
I have to query for total amount of a column using an aggregate function. The column data type is NVARCHAR(MAX). How can I convert it to Integer?
I have tried this:
SELECT SUM(CAST(amount AS INT)),
branch
FROM tblproducts
WHERE id = 4
GROUP BY branch
...but I'm getting:
Conversion failed when converting the nvarchar value '3600.00' to data type int.
3600.00 is not integer so CAST via float first
sum(CAST(CAST(amount AS float) AS INT))
Edit:
Why float?
no idea of precision or scale across all rows: float is the lesser evil perhaps
empty string will cast to zero for float, fails on decimal
float accepts stuff like 5E-02, fails on decimal
In addition to gbn's answer, you need to protect against non-numeric cases:
sum(CASE WHEN ISNUMERIC(Amount)=1 THEN CAST(CAST(amount AS float) AS INT)END )
SELECT sum(Try_Parse(amount as Int Using 'en-US')),
branch
FROM tblproducts
WHERE id = 4
GROUP BY branch
create table test_int
(
num bigint
)
insert into test_int (num)
values (4096);
My task is to calculate 4096/1024/1024 and get decimal answer. Ok, int doesn't store values after dot, so:
select CAST (num as decimal)/1024/1024 AS decimal, ROUND ((CAST (num as decimal)/1024/1024),4,1) AS numeric from test_int
First one is pure resault, second one is after rounding:
decimal numeric
0.00390625000 0.00390000000
The task is to remove empty zeroes after values.
select convert(decimal(25,5), 4096/1024/1024 ,0)
returns 0.00000.
So how can I get 0.0039 instead of 0.00390000000?
Thanks in advance for any kind of help.
Cast the result to FLOAT.
Query
SELECT
CAST
(
CAST(num as decimal)/1024/1024
AS FLOAT
) AS decimal,
CAST
(
ROUND((CAST (num as decimal)/1024/1024),4,1)
AS FLOAT
) AS numeric
from test_int;
Result
+---------------+---------------+
| decimal | numeric |
+---------------+---------------+
| 0.00390625 | 0.0039 |
+---------------+---------------+
SQL Fiddle
This one will work , but if i'm not mistaken , this will only work for 2008 version and above.
SELECT CONVERT(DOUBLE PRECISION, 0.00390000000)
result: 0.0039