简体   繁体   中英

How do not to round the number in SQL

I have a query like this:

Select Customer,JobType,sum(SThours),
sum(OThours),SortMonth,
str((sum(OThours)/sum(SThours)),5,2)AS Ratios 
from #data
group by Customer,JobType,SortMonth


Sum (SThours): 688
sum(OThours): 618

The ratio should be 618/688=0.90 but my result is 1.00

I am new to SQL, and I need help. Thanks.

Try casting one or other side of the division to a float - to force floating point rather than integer division.

SELECT
  Customer,
  JobType,
  sum(SThours),
  sum(OThours),
  SortMonth,
  str((CAST(sum(OThours) AS FLOAT)/sum(SThours)),5,2) AS Ratios
FROM
  #data
GROUP BY
  Customer,
  JobType,
  SortMonth

Your problem is that you're performing an integer division, which will always result in an integer value in return. You should cast the sums to a floating point numeric value (decimal should work) before dividing them.

Try casting the number to decimal

SELECT
  Customer,
  JobType,
  sum(SThours),
  sum(OThours),
  SortMonth,
  str((CAST(sum(OThours) AS DECIMAL)/sum(SThours) ),5,2) AS Ratios
FROM
   #data
GROUP BY
  Customer,  JobType,  SortMonth

Try this sample fiddle

it is simple example showing getting decimal values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM