Skip to content

[MySQL] 心得筆記(5) Number Function: ABS, CEIL, FLOOR, MOD, POWER, SIGN, TRUNCATE, SQRT

在 SQL 當中,在處理『數值』方面存在著許多非常好用的指令,今天就介紹以下指令:

  • ABS(): 計算絕對值
  • CEIL(): 無條件進入至整數
  • FLOOR(): 無條件捨去至整數
  • ROUND(n1, n2): 將 n1 四捨五入至小數第 n2 位
  • TRUNCATE(n1, n2): 將 n1 無條件捨去至小數第 n2 位
  • MOD(n1, n2): 求 n1 除以 n2 之餘
  • POWER(n1, n2): 求 n1 的 n2 次方
  • SIGN(): 判斷值的正負
  • SQRT(): 返回輸入值的根

那麼以下,我們便實際測試看看這些指令。


事前準備

首先,我們有以下這樣的一張表:

SIDn
110
220
3-5
45.36

我們以下都以張表來示範。


ABS

計算出絕對值。

select n, abs(n) from num where n = -5;



Output:

nabs(n)
-55

CEIL

無條件進位至整數。

select n, ceil(n) from num where SID = 4;



Output:

nceil(n)
5.366

FLOOR

無條件捨去至整數。

select n, floor(n) from num where SID = 4;



Output:

nfloor(n)
5.365

ROUND

自行決定四捨五入至小數幾位數。

select n, round(n, 1) from num where SID = 4;



Output:

nfloor(n)
5.365.4

這裡是自行決定四捨五入至小數第一位。


TRUNCATE

自行決定無條件捨去至小數第幾位。

select n, truncate(n, 1) from num where SID = 4;



Output:

ntruncate(n)
5.365.3

這裡是自行決定無條件至小數第一位。


MOD

求餘數。

select n, mod(n, 3) from num where n = 10;



Output:

nmod(n)
101

10 除以 3 餘 1。


POWER

求數值的次方。

select n, power(n, 2) from num where n = 10;



Output:

npower(n)
10100

SIGN

判斷正負。

select n, sign(n) from num where n = -5;



Output:

nsign(n)
-5-1

-5 為負數。


SQRT

求根。

select n, sqrt(n) from num where n = 10;



Output:

nsqrt(n)
10 3.1622776601683795

常用的數值 function 差不多就以上這幾種,若是熟練掌握以後,想必對於查找、顯示數值會有很大的幫助。

Leave a Reply