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条回答
▲ chillily
2楼-- · 2020-06-08 19:31

At least in MySQL (if it helps), if you want to use float numbers you had to use a type float field, not the regular int fields.

查看更多
对你真心纯属浪费
3楼-- · 2020-06-08 19:33

Its probably overkill to do this, but you may wish to consider casting all values to floats to ensure accuracy at all phases.

(100.0 * ( [TotalVisit1]+0.0 )/([TotalVisits]+0.0) ) as Visit1percent

Note, you really need to put code in here for the case that TotalVisits == 0 or you will get a division by 0 answer.

查看更多
贼婆χ
4楼-- · 2020-06-08 19:35
convert(decimal(5,2),(100 * convert(float,[TotalVisit1])/convert(float,[TotalVisits]))) AS Visit1percent

Ugly, but it works.

查看更多
Emotional °昔
5楼-- · 2020-06-08 19:39

Just add a decimal to the 100

(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent

this forces all processing to happen in floats... if you want the final output as text, and truncated for display to only one decimal place, use Str function

Str( 100.0 * [TotalVisit1]/[TotalVisits], 4, 1 ) AS Visit1percent
查看更多
仙女界的扛把子
6楼-- · 2020-06-08 19:42

This works perfectly for me:

CAST((1.0 * SUM(ColumnA) /COUNT(ColumnB)) as decimal(5,2))

Hope it helps someone out there in the world.

查看更多
时光不老,我们不散
7楼-- · 2020-06-08 19:44

Try This:

(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
查看更多
登录 后发表回答