四舍五入与截断数字

SQL Server 中级

Ginger Grant

Instructor

在 T-SQL 中四舍五入

ROUND(number, length [,function])
SQL Server 中级

在 T-SQL 中四舍五入

SELECT DurationSeconds, 
ROUND(DurationSeconds, 0) AS RoundToZero, 
ROUND(DurationSeconds, 1) AS RoundToOne
FROM Incidents
+--------------------+------------------+------------------+     
|DurationSeconds     |RoundToZero       |RoundToOne        |     
+--------------------+------------------+------------------+     
|121.6480            |122.0000          |121.6000          |
|170.3976            |170.0000          |170.4000          |
|336.0652            |336.0000          |336.1000          |
...
+--------------------+------------------+------------------+
SQL Server 中级

小数点左侧的四舍五入

SELECT DurationSeconds, 
ROUND(DurationSeconds, -1) AS RoundToTen, 
ROUND(DurationSeconds, -2) AS RoundToHundred
FROM Incidents
+--------------------+------------------+------------------+     
|DurationSeconds     |RoundToTen        |RoundToHundred    |     
+--------------------+------------------+------------------+     
|121.6480            |120.0000          |100.0000          |
|170.3976            |170.0000          |200.0000          |
|336.0652            |340.0000          |300.0000          |
...
+--------------------+------------------+------------------+
SQL Server 中级

截断数字

截断

17.85 $\rightarrow$ 17

四舍五入

17.85 $\rightarrow$ 18

SQL Server 中级

用 ROUND() 截断

当指定第三个参数时,ROUND() 可用于截断值

ROUND(number, length [,function])
  • 将第三个参数设为非零值
SQL Server 中级

在 T-SQL 中截断

SELECT Profit, 
ROUND(DurationSeconds, 0) AS RoundingtoWhole, 
ROUND(DurationSeconds, 0, 1) AS Truncating 
FROM Incidents
+--------------------+------------------+------------------+    
|Profit              |RoundingtoWhole   |Truncating        |
+--------------------+------------------+------------------+  
|15.6100             |16.0000           |15.0000           |
|13.2444             |13.0000           |13.0000           |
|17.9260             |18.0000           |17.0000           |
...
+--------------------+------------------+------------------+  

截断会在指定位数后直接去掉所有数字

SQL Server 中级

Passons à la pratique !

SQL Server 中级

Preparing Video For Download...