Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get percentage in TSQL when dividing 2 integers?

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?

like image 677
Richard77 Avatar asked May 23 '16 16:05

Richard77


People also ask

How do you divide two numbers in SQL?

The SQL divide ( / ) operator is used to divide one expressions or numbers by another.

How do you get the decimal value when dividing in SQL?

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 ...

How do you calculate percent discount in SQL query?

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.


1 Answers

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
like image 124
Serg Avatar answered Nov 19 '22 17:11

Serg