How do I calculate percentages with decimals in SQ

2020-06-08 19:10发布

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

标签: sql decimal sum
11条回答
你好瞎i
2楼-- · 2020-06-08 19:44
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.

查看更多
ら.Afraid
3楼-- · 2020-06-08 19:45

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

查看更多
神经病院院长
4楼-- · 2020-06-08 19:46
CAST(ROUND([TotalVisit1]*100.0/[TotalVisits],2)as decimal(5,2)) as Percentage


Not ugly and work better and fast , enjoy it!

查看更多
做个烂人
5楼-- · 2020-06-08 19:49

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                     
查看更多
三岁会撩人
6楼-- · 2020-06-08 19:51

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)

查看更多
登录 后发表回答