sql的函數是有很多的,我就寫一下關鍵的幾個函數。當時在上課的時候,老師有給一個課件,裏面包含了比較全的常見的函數,有需要的筒子們可以下載:網盤地址:鏈接:https://pan.baidu.com/s/1HcCuxIU5hZiLrlZntabuaw 密碼:g3lr
目錄
一、字符串函數
- concat(str1,str2,…):合併字符串
【注意】合併時,其中有個字段是null那麼返回結果也是null,null不代表空格,需要空格,可以寫‘ ’
二、數學函數
1、floor(n):向下取整
【例】select floor(1.23); -- 1
Select floor(-1.23); -- -2
2、Ceiling(n):向上取整
【例】select ceiling(1.23); -- 2
Select ceiling(-1.23); -- -1
3、Rand([n]):返回範圍0到1內的隨機數,n作爲初始值,也叫隨機種子。n是固定隨機數多少。
【例】select rand(2); -- 0.65558664465490 #固定了n,在其他任何時候運算得到的值是一樣的,避免模型在不同時候運算因隨機數而導致結果不同。
三、時期時間函數
- date_format(date,format):轉換時間格式
四、分組合並函數
1、group_concat([distinct] str [order by str asc/desc] [separator])
將group by 產生的同一個分組的值合併成一個字符串。
【參數】
distinct:去重
orderby:排序
separato:指定分割符號
【例子】
Select deptno, group_concat(distinct ename order by sal desc separator '/')
from emp
group by deptno;
【注意】
- 需要和group by 一起使用;
- Group_concat()函數會忽略空值。
五、邏輯函數
1、ifnull(expression,alt_value)
判斷第一個參數是否爲空值NULL,如果爲NULL則返回第二個參數值,如果不爲NULL則返回自己。常用於代替空值爲0場景。
2、If(expr1,expr2,expr3)
判斷如果expr1爲true,則返回expr2,如果爲false,則返回expr3。
3、Case when expr1 then expr2 [when expr3 then expr4 … else expr5 ] end
判斷如果expr1爲true,則返回expr2,如果爲expr1爲false且expr3爲true,則返回expr4…
六、開窗函數
1、開窗函數名([<字段名>]) over( [partition by <分組字段>] [order by <排序字段> [desc] ] [<滑動窗口>])
【注意】
- over和groupby分組的意義是一樣的,都是分組統計;
- 區別在於group by 是針對分組後的組統計,返回的結果是一個組一個結果,而over是對每條記錄執行統計,即每行記錄後都有結果,結果一樣也是分組後統計的。也可以理解爲:group by的select只能顯示分組字段和聚合函數,而分窗over可以顯示所有字段。
- OVER關鍵字後的括號中還經常添加選項用以改變進行聚合運算的窗口範圍。如果OVER關鍵字後的括號中的選項爲空,則代表不做任何分組。
- 當over中指定分區和排序,但沒有指定滑動窗口(rows),默認計算的是分區內第一行到當前行的值。
【例】
2、滑動窗口的7種寫法
- Rows between 1 preceding and current row: 前一行和當前行共兩行記錄
- Rows between current row and 1 following: 當前行和後一行共兩行記錄
- Rows between 1 preceding and 1 following:前一行、當前行、後一行共三行記錄
- Rows unbounded preceding:分區中第一行到當前行
- Rows between unbounded preceding and current row:分區中第一行到當前行
- Rows between current row and unbounded following:分期中當前行到最後一行
- Rows between unbounded preceding and unbounded following:分區中所有行記錄,等同於不寫
【例子】
select *,avg(sal) over(partition by deptno order by hiredate rows between 1 preceding and 1 following) 部門平均工資 from emp;
七、序號函數
- row_number():顯示分區中不重複不間斷的序號
- dense_rank():顯示分區中重複不間斷的序號
- Rank():顯示分區中重複間斷的序號
【注意】
row_number():數值相等,排名不會相等,會根據數值插入時間排名
dense_rank():數值相等,排名會相等,下個排名不會間隔
rank():數值相等,排名會相等,下個排名會間隔