備註:測試資料庫版本為mysql 8.0
如需要scott使用者下建表及錄入資料語句,可參考:
scott建表及錄入資料sql指令碼
一.需求
把資料變為固定數目的桶。
例如,把錶emp中的員工編組為4桶。
其結果集應該如下所示:
| grp | empno | ename |
| 1 | 7566 | jones |
| 1 | 7788 | scott |
| 1 | 7900 | james |
| 2 | 7369 | smith |
| 2 | 7654 | martin |
| 2 | 7839 | king |
| 2 | 7902 | ford |
| 3 | 7499 | allen |
| 3 | 7698 | blake |
| 3 | 7844 | turner |
| 3 | 7934 | miller |
| 4 | 7521 | ward |
| 4 | 7782 | clark |
| 4 | 7876 | adams |
二.解決方案
mysql 8.0開始支援視窗函式,ntile直接提供了建立"桶"的函式,這個就很簡單了。
如果不使用ntile函式,也可以給每行分等級,然後在表示式中使用等級對n的模(n是要建立的同屬),以確定該行落入哪個桶內。
2.1 臨時表方法
select mod(count(*),4) +1 as grp,
e.empno,
e.ename
from emp e, emp d
where e.empno >= d.empno
group by e.empno,e.ename
order by 1;
測試記錄:
mysql> select mod(count(*),4) +1 as grp,
-> e.empno,
-> e.ename
-> from emp e, emp d
-> where e.empno >= d.empno
-> group by e.empno,e.ename
-> order by 1;
| grp | empno | ename |
| 1 | 7566 | jones |
| 1 | 7788 | scott |
| 1 | 7900 | james |
| 2 | 7369 | smith |
| 2 | 7654 | martin |
| 2 | 7839 | king |
| 2 | 7902 | ford |
| 3 | 7499 | allen |
| 3 | 7698 | blake |
| 3 | 7844 | turner |
| 3 | 7934 | miller |
| 4 | 7521 | ward |
| 4 | 7782 | clark |
| 4 | 7876 | adams |
14 rows in set (0.00 sec)
2.2 mysql 8.0 視窗函式方法
select mod(row_number() over w, 4) + 1 as grp,
empno,
ename
from emp
window w as (order by empno)
order by 1;
測試記錄:
mysql> select mod(row_number() over w, 4) + 1 as grp,
-> empno,
-> ename
-> from emp
-> window w as (order by empno)
-> order by 1;
| grp | empno | ename |
| 1 | 7566 | jones |
| 1 | 7788 | scott |
| 1 | 7900 | james |
| 2 | 7369 | smith |
| 2 | 7654 | martin |
| 2 | 7839 | king |
| 2 | 7902 | ford |
| 3 | 7499 | allen |
| 3 | 7698 | blake |
| 3 | 7844 | turner |
| 3 | 7934 | miller |
| 4 | 7521 | ward |
| 4 | 7782 | clark |
| 4 | 7876 | adams |
14 rows in set (0.00 sec)
2.3 mysql 8.0 ntile函式方法
select ntile(4) over w as 'grp',
empno,
ename
from emp
window w as (order by empno)
測試記錄:
mysql> select ntile(4) over w as 'grp',
-> empno,
-> ename
-> from emp
-> window w as (order by empno)
| grp | empno | ename |
| 1 | 7369 | smith |
| 1 | 7499 | allen |
| 1 | 7521 | ward |
| 1 | 7566 | jones |
| 2 | 7654 | martin |
| 2 | 7698 | blake |
| 2 | 7782 | clark |
| 2 | 7788 | scott |
| 3 | 7839 | king |
| 3 | 7844 | turner |
| 3 | 7876 | adams |
| 4 | 7900 | james |
| 4 | 7902 | ford |
| 4 | 7934 | miller |
14 rows in set (0.00 sec)
mysql的預定義語句 MySQL預處理語句
預製語句的sql語法基於三個sql語句 prepare stmt name from preparable stmt execute stmt name using var name var name prepare stmt name prepare語句用於預備乙個語句,並賦予它名稱stmt na...
mysql建立 mysql建立新使用者
1.新建使用者 1.1 登入mysql mysql u root p 密碼 1.2 建立使用者 mysql insert into mysql.user host,user,password values localhost test password 1234 這樣就建立了乙個名為 test 密碼...
mysql 建立使用者指令碼 Mysql使用者建立指令碼
我試圖自動化mysql使用者建立過程。我想到建立乙個包含mysql使用者建立語句的臨時檔案,那麼我會這樣稱呼 mysql u root proot 這裡是我的臨時檔案的內容 drop database if exists mytestdatabase create database mytestda...