MYSQL-實現ORACLE 和SQLserver數據中- row_number() over(partition by ) 分組排序功能


  網上看見了好多例子都基本上是一樣的,沒有過多的解釋,對於一個初學MySQL來說有點難,我把部分轉摘過來如下 原文:http://www.cnblogs.com/buro79xxd/archive/2012/08/29/2662489.html

要求目標:1.確定需求: 根據部門來分組,顯示各員工在部門里按薪水排名名次.

創建表格:2.來創建實例數據:

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);

數據效果圖:

實現 3. http://www.kaishixue.com/mysql/14.html 帖子中SQL的實現

SELECT
empid,
deptid,
salary,
rank
FROM
(
SELECT
heyf_tmp.empid,
heyf_tmp.deptid,
heyf_tmp.salary,

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
@pdept := NULL ,@rank := 0
) a
) result;

對於這一段我是羞澀難懂的,雖然實現了需求的結果,看了很久才明白過來,現在我小修改一下 用存儲過程實現
 

CREATE PROCEDURE testrank ()
BEGIN
SET @num = 0;
SET @pdept = NULL;
SELECT
result.empid,
result.deptid,
result.salary,
result.rank
FROM
(
SELECT
s.empid,
s.deptid,
s.salary,

IF (
@pdept = s.deptid ,@num :=@num + 1 ,@num := 1
) AS rank,
@pdept := s.deptid
FROM
heyf_t10 s
ORDER BY
s.deptid ASC,
s.salary DESC
) result;

END

執行 語句 call testrank();

結果圖:

另外一種思路是上文鏈接的作者的如下:

SELECT
h.`empid`,
h.`deptid`,
h.`salary`,
count(*) AS rank
FROM
heyf_t10 AS h
LEFT OUTER JOIN heyf_t10 AS r ON h.deptid = r.deptid
AND h.`salary` <= r.`salary`
GROUP BY
h.`empid`,
h.`deptid`,
h.`salary`
ORDER BY
h.deptid,
h.salary DESC;

他們誰好誰差不清楚 反正多了一個思路。這樣就是好的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM