I have seen many examples on the Internet, all of which are basically the same, without too much explanation. It is a bit difficult for a beginner to learn MySQL. I have copied some of the original texts as follows: http://www.cnblogs.com/buro79xxd/archive/ 2012/08/29/2662489.html
Requirements and goals: 1. Determine the demand: Group according to the department, and display the rank of each employee according to the salary in the department.
Create table: 2. To create instance data:
drop table if exists heyf_t10;
(9,50,7500.00);
Data renderings:
Implementation 3. Implementation of SQL in http://www.kaishixue.com/mysql/14.html post
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;
他们谁好谁差不清楚 反正多了一个思路。这样就是好的。