四捨五入與截斷數值

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])
  • 第三個參數設為非 0 的數值。
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 中級

一起來練習吧!

SQL Server 中級

Preparing Video For Download...