I'd like to display this division as a percent.
SELECT a * 100/b
FROM myTable
WHERE condition
Here, for instance, a = 170, b = 288. a / b = 0.590277777778
.
I'd like to return 59,02
. What I'm getting is only 59
. How to get both parts?
The SQL divide ( / ) operator is used to divide one expressions or numbers by another.
SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM ..... SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM ..... SELECT CAST(Col1 as decimal(10,2)) / CAST(col2 as decimal(10,2)) as [Value] FROM ...
The formula will need to be something like: col1 * 0. col2 (both columns 1&2 can be null). Col1 is the GrossAmount(decimal(10,2) and Col2(smallint) is the percent discount.
Sql Server sees only integer arguments and returns integer result. Make one of two first arguments numeric / decimal
select a * 100./b
or
select cast(cast(a as decimal(18,4)) * 100/b as decimal(18,2))
this will not help:
select a/b*100.
because of the order of operations first opeation ( division )is still integer.
Test case to play with
declare @a int=170,
@b int=288;
select cast(@a as decimal)*100/@b --59.02777777777
, @a*100./@b --59.02777777777
, cast (@a*100./@b as decimal(18,2)) --59.03
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With