国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

MYSQL怎么實(shí)現分組排序功能

發(fā)布時(shí)間:2021-09-27 17:43 來(lái)源:億速云 閱讀:0 作者:chen 欄目: Mysql 歡迎投稿:712375056

這篇文章主要講解了“怎么實(shí)現分組排序功能”,文中的講解內容簡(jiǎn)單清晰,易于學(xué)習與理解,下面請大家跟著(zhù)小編的思路慢慢深入,一起來(lái)研究和學(xué)習“MYSQL怎么實(shí)現分組排序功能”吧!

由于MYSQL沒(méi)有提供類(lèi)似ORACLE中OVER()這樣豐富的分析函數. 所以在MYSQL里需要實(shí)現這樣的功能,我們只能用一些靈活的辦法:

1.首先我們來(lái)創(chuàng )建實(shí)例數據:

drop table if exists heyf_t10;
create table heyf_t10 (empid int ,deptid int ,salary decimal(10,2) );

insert into heyf_t10 values
(1,10,5500.00),
(2,10,4500.00),
(3,20,1900.00),
(4,20,4800.00),
(5,40,6500.00),
(6,40,14500.00),
(7,40,44500.00),
(8,50,6500.00),
(9,50,7500.00);

2. 確定需求: 根據部門(mén)來(lái)分組,顯示各員工在部門(mén)里按薪水排名名次.

顯示結果預期如下:

+-------+--------+----------+------+
| empid | deptid | salary   | rank |
+-------+--------+----------+------+
|     1 |     10 |  5500.00 |    1 |
|     2 |     10 |  4500.00 |    2 |
|     4 |     20 |  4800.00 |    1 |
|     3 |     20 |  1900.00 |    2 |
|     7 |     40 | 44500.00 |    1 |
|     6 |     40 | 14500.00 |    2 |
|     5 |     40 |  6500.00 |    3 |
|     9 |     50 |  7500.00 |    1 |
|     8 |     50 |  6500.00 |    2 |
+-------+--------+----------+------+


3. SQL 實(shí)現

select empid,deptid,salary,rank from (
select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,
if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,
@pdept:=heyf_tmp.deptid
from (
select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc
) heyf_tmp ,(select @rownum :=0 , @pdept := null ,@rank:=0) a ) result
;

4. 結果演示

mysql> select empid,deptid,salary,rank from (
   -> select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,
   -> if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,
   -> @pdept:=heyf_tmp.deptid
   -> from (
   -> select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc
   -> ) heyf_tmp ,(select @rownum :=0 , @pdept := null ,@rank:=0) a ) result
   ->  ;
+-------+--------+----------+------+
| empid | deptid | salary   | rank |
+-------+--------+----------+------+
|     1 |     10 |  5500.00 |    1 |
|     2 |     10 |  4500.00 |    2 |
|     4 |     20 |  4800.00 |    1 |
|     3 |     20 |  1900.00 |    2 |
|     7 |     40 | 44500.00 |    1 |
|     6 |     40 | 14500.00 |    2 |
|     5 |     40 |  6500.00 |    3 |
|     9 |     50 |  7500.00 |    1 |
|     8 |     50 |  6500.00 |    2 |
+-------+--------+----------+------+
9 rows in set (0.00 sec)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。

日本极品少妇XXXX| 久久天天躁狠狠躁夜夜96流白浆| 久久国产福利播放| 国产成人综合色视频精品| 国产9 9在线 | 中文| 在线人成免费视频69国产|